所以我想将 Person 放入数组列表中,但我需要使用流 我有 csv 文件,可以给我信息 身份证;姓名;性别 以及使用那里的 id 将它们变成 Person 对象的方法,
private Person readCSVLines(int id);
但我想创建一个方法,给我一个数组列表,其中包含所有我知道的 807 id 并且不会再有
我使用 toMap 尝试了这个,但它给了我一张 map ,但我只想要一个 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());
}
}
另外,注意你的方法应该有接口(interface)作为返回类型(List
)而不是具体实现(ArrayList
)
关于java - 如何从 Intstream 创建 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59522849/