java - 如何从 Intstream 创建 ArrayList
问题描述
所以我想将Person放入一个数组列表,但我需要使用流我有 csv 文件,它给我 infomartions id;name;sex 和一种使用那里的 id 将这些转换为Person对象的方法,
private Person readCSVLines(int id);
但我想创建一种方法,给我一个数组列表,我知道有 807 id 并且不会再有
我使用 toMap 尝试了这个,但它给了我一张地图,但我只想要一个 ArrayList:
public ArrayList<Person> getAllPerson() {
try (IntStream stream = IntStream.range(1, personmax)) { // personmax is 807 here
return stream.boxed().collect(
Collectors.toMap(
i -> i,
this::readCSVLines,
(i1, i2) -> {
throw new IllegalStateException();
},
ArrayList::new
)
);
}
}
解决方案
在您的情况下,您只需使用 遍历所有行IntStream.range(from, to)
并将每个行号转换为从 csv 读取的对象.mapToObj()
。在这种情况下使用boxed()
函数是多余的。最后,你需要的是
public List<Person> getAllPerson() {
return IntStream
.range(1, personmax) // personmax is 807 here
.mapToObj(this::readCSVLines)
.collect(Collectors.toList());
}
}
另外,请注意,您的方法应该将接口作为返回类型 ( List
) 而不是具体实现 ( ArrayList
)
推荐阅读
- jmeter - 测量 API 的响应时间
- cmake - 在 QtCreator 中运行时 CMake 找不到 ninja
- android - 使用 Android volley 向 laravel 发送数据
- python - 如何获取对 ReadVariableOp 正在读取的变量对象的引用?
- node.js - 从 puppeteer 到 ffmpeg 的管道屏幕截图
- javascript - 如何在 javascript 中使用回调函数结果填充数组?
- c# - 如何避免 ef 以上业务逻辑类中的重复代码?
- javascript - EDGE 在显示键盘输入时滞后
- azure-devops - 用于自动化而不是个人访问令牌的用户
- python - 在 matplotlib 图中配置网格线