问题描述
我试图将整数列表转换为用逗号分隔的整数组成的字符串.
I was trying to convert list of Integers into String of comma separated integers.
Collectors.joining(CharSequence delimiter)-返回一个收集器,该收集器以相遇顺序连接由指定分隔符分隔的输入元素.
List<Integer> i = new ArrayList<>(); // i.add(null);
for (int j = 1; j < 6; j++) {
i.add(j);
}
System.out.println(i.stream().collect(Collectors.joining(","))); // Line 8
第8行出现错误.
Java 8中的流有没有办法做到这一点?
Is there any way to do this by streams in Java 8?
更新:
如果我用"1","2","3","4","5"
创建一个字符串列表.可以.
If i create a list of string with "1", "2", "3","4","5"
. it works.
推荐答案
是.但是,对于 Stream< Integer>
,没有 Collectors.joining
;您需要一个 Stream< String>
,因此您应先 map
进行收集.像
Yes. However, there is no Collectors.joining
for a Stream<Integer>
; you need a Stream<String>
so you should map
before collecting. Something like,
System.out.println(i.stream().map(String::valueOf)
.collect(Collectors.joining(",")));
哪个输出
1,2,3,4,5
此外,您可以通过多种方式生成 Stream< Integer>
.
Also, you could generate Stream<Integer>
in a number of ways.
System.out.println(
IntStream.range(1, 6).boxed().map(String::valueOf)
.collect(Collectors.joining(","))
);
这篇关于将整数列表转换为逗号分隔的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!