使用Java流创建具有动态值的员工列表

我有一个用例,其中我必须创建ID递增的默认雇员列表,

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

我没有可以使用流的任何收藏。我们可以通过功能性方式做到吗?

评论
  • xnobis
    xnobis 回复

    You are looking for IntStream,

    IntStream.rangeClosed(1, 100)
            .boxed()
            .map(i->new Employee(i, "a"+i))
            .collect(Collectors.toList());
    
  • gomnis
    gomnis 回复

    You can use IntStream with rangeClosed(int startInclusive, int endInclusive) to generate the count

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