首页 > 解决方案 > 使用 Java 流创建具有动态值的员工列表

问题描述

我有一个用例,我必须创建具有递增 id 的默认员工列表,

List<Employee> employeeList = new ArrayList<>();
int count = 0;
while (count++ <= 100){
    Employee employee = new Employee(count, "a"+count);
    employeeList.add(employee);
}

我没有任何可以使用流的集合。我们可以用功能性的方式来做吗?

标签: javafunctional-programmingjava-stream

解决方案


您可以使用IntStreamrangeClosed(int startInclusive, int endInclusive)生成计数

List<Employee> employeeList = IntStream.rangeClosed(0,100)
                                       .boxed()
                                       .map(count-> new Employee(count, "a"+count))
                                       .collect(Collectors.toList());

或者你可以使用Stream.iterate

List<Employee> employeeList = Stream.iterate(0, n -> n + 1)
                                    .limit(100)
                                    .map(i -> new Employee(i, "a" + i))
                                    .collect(Collectors.toList())

推荐阅读