java - 使用 Java 流创建具有动态值的员工列表
问题描述
我有一个用例,我必须创建具有递增 id 的默认员工列表,
List<Employee> employeeList = new ArrayList<>();
int count = 0;
while (count++ <= 100){
Employee employee = new Employee(count, "a"+count);
employeeList.add(employee);
}
我没有任何可以使用流的集合。我们可以用功能性的方式来做吗?
解决方案
您可以使用IntStream来rangeClosed(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())
推荐阅读
- performance - 加快批处理文件解析时间
- python-3.x - 具有特定对象属性的全局缓存作为python中的输入
- c++ - 删除不同线程中的对象会导致崩溃?
- ios - 让 UITableViewCell 短暂闪烁
- vhdl - VHDL 信号声明麻烦?
- excel - 如何在 vbd 编辑器中创建/添加重复代码,而不是保存在个人工作簿中
- javascript - 当天为 31 且下个月没有它时,javascript date setMonth 失败
- django - 在 django REST 中序列化相关外键对象的详细字段?
- node.js - 机器人框架异步问题
- json - Discordjs 聊天过滤器