Create List of Employees with dynamic values using Java streams

拟墨画扇 提交于 2020-06-27 06:31:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!