问题
I have use case where I have to create List of default employees with incrementing id,
List<Employee> employeeList = new ArrayList<>();
int count = 0;
while (count++ <= 100){
Employee employee = new Employee(count, "a"+count);
employeeList.add(employee);
}
I don't have any collection on which I could use stream. Can we do it in functional way?
回答1:
You can use IntStream with rangeClosed(int startInclusive, int endInclusive)
to generate the count
List<Employee> employeeList = IntStream.rangeClosed(0,100)
.boxed()
.map(count-> new Employee(count, "a"+count))
.collect(Collectors.toList());
Or you can use Stream.iterate
List<Employee> employeeList = Stream.iterate(0, n -> n + 1)
.limit(100)
.map(i -> new Employee(i, "a" + i))
.collect(Collectors.toList())
来源:https://stackoverflow.com/questions/61412034/create-list-of-employees-with-dynamic-values-using-java-streams