2

I need to populate list of class Student:

class Student {
    String firstName;
    String lastName;
    public Student(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

Here is the generator method signature:

public List<Student> generateRandomStudents(int quantity) {
List<Student> students;
// List is populated by required quantity of students
return students;

What I have tried:

List<Student> students = Stream
    .of(new Student(getRandomStringFromFile("firstnames.txt"), getRandomStringFromFile("lastnames.txt")))
    .limit(quantity)
    .collect(Collectors.toList());

creates only 1 student. 2) Tried using Stream.generate, but it works only with Supplier and I can't use my arguments for the constructor.

2
  • 3
    Can you show how you have tried Stream.generate? You do need a supplier here. Commented Apr 15, 2021 at 11:27
  • 2
    ..or think of using IntStream.range as if you would loop, mapping to a new Student object each time. Commented Apr 15, 2021 at 11:29

1 Answer 1

3

Stream.of(new Student(..)) generates a stream of just that single element.

What you instead want is to have a Supplier<Student> which can produce a random Student, and then use Stream.generate(Supplier<?>) to generate an endless stream of random students (which you later limit):

Supplier<Student> randomStudent = () -> new Student(
        getRandomStringFromFile("firstnames.txt"), 
        getRandomStringFromFile("lastnames.txt"));

List<Student> students = Stream.generate(randomStudent)
        .limit(quantity)
        .collect(Collectors.toList());

or inlined:

List<Student> students = Stream
        .generate(() -> new Student(
                getRandomStringFromFile("firstnames.txt"),
                getRandomStringFromFile("lastnames.txt")))
        .limit(quantity)
        .collect(Collectors.toList());
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.