I have use case where I have to create List of default employees with incrementing id,
List 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?
解决方案
You can use IntStream with rangeClosed(int startInclusive, int endInclusive) to generate the count
List employeeList = IntStream.rangeClosed(0,100)
.boxed()
.map(count-> new Employee(count, "a"+count))
.collect(Collectors.toList());
Or you can use Stream.iterate
List employeeList = Stream.iterate(0, n -> n + 1)
.limit(100)
.map(i -> new Employee(i, "a" + i))
.collect(Collectors.toList())