我需要填充类(class)学生列表:
class Student {
String firstName;
String lastName;
public Student(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
这是生成器方法签名:
public List<Student> generateRandomStudents(int quantity) {
List<Student> students;
// List is populated by required quantity of students
return students;
我尝试过的:
List<Student> students = Stream
.of(new Student(getRandomStringFromFile("firstnames.txt"), getRandomStringFromFile("lastnames.txt")))
.limit(quantity)
.collect(Collectors.toList());
仅创建 1 名学生。 2)尝试使用 Stream.generate,但它仅适用于供应商,并且我无法将我的参数用于构造函数。
最佳答案
Stream.of(new Student(..))
生成仅包含该单个元素的流。
您想要的是 Supplier<Student>
它可以产生随机 Student
,然后使用Stream.generate(Supplier<?>)
生成源源不断的随机学生流(稍后limit
):
Supplier<Student> randomStudent = () -> new Student(
getRandomStringFromFile("firstnames.txt"),
getRandomStringFromFile("lastnames.txt"));
List<Student> students = Stream.generate(randomStudent)
.limit(quantity)
.collect(Collectors.toList());
或内联:
List<Student> students = Stream
.generate(() -> new Student(
getRandomStringFromFile("firstnames.txt"),
getRandomStringFromFile("lastnames.txt")))
.limit(quantity)
.collect(Collectors.toList());
关于java - 使用带参数的构造函数填充对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67107565/