本文介绍了使用Java流创建具有动态值的员工列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

您可以使用 IntStream rangeClosed(int startInclusive, int endInclusive)一起生成计数

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());

或者您可以使用 Stream.iterate

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

这篇关于使用Java流创建具有动态值的员工列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 02:31