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?
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())
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.