使用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());
点赞
评论