Reputation: 85
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.
Upvotes: 2
Views: 258
Reputation: 15706
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());
Upvotes: 3