目前我有:
String a = "123.5950,555,5973.1,6321.905,6411.810000000001,6591.855"
Run Code Online (Sandbox Code Playgroud)
我可以将它转换为字符串数组列表然后转换为Longs的数组列表:
ArrayList<String> vals = new ArrayList<String>(Arrays.asList(a.split(","));
ArrayList<Long> longs = new ArrayList<>();
for(String ks : vals){
longs.add(Long.parseLong(ks));
}
Run Code Online (Sandbox Code Playgroud)
我尝试这样做是Stream为了让它更"有趣",但似乎无法成功:
ArrayList<Long> longs = a.stream().map(Long::parseLong).collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
我不认为for循环非常优雅,我怎么能用它Stream?
编辑:复制到原始字符串错误
Joa*_*ado 10
您需要从以下结果创建流String.split:
final List<Long> longs = Arrays
.stream(a.split(","))
.map(Long::parseLong)
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
此外,Collectors.toList()将返回List接口,而不是具体实现ArrayList.
如果你真的需要一个数组列表,你需要复制它:
new ArrayList<>(longs);
Run Code Online (Sandbox Code Playgroud)
编辑:
正如@shmosel指出的那样,你可以直接收集到数组列表Collectors.toCollection(ArrayList::new)