Convert list of integer into comma separated string?

Tags: , , , ,

I was trying to convert list of Integers into String of comma separated integers.

Collectors.joining(CharSequence delimiter) – Returns a Collector that concatenates the input elements, separated by the specified delimiter, in encounter order.

List<Integer> i = new ArrayList<>();    //  i.add(null);
for (int j = 1; j < 6; j++) {
System.out.println(","))); // Line 8

I am getting error in line no 8.

Is there any way to do this by streams in Java 8?


If i create a list of string with "1", "2", "3","4","5". it works.


Yes. However, there is no Collectors.joining for a Stream<Integer>; you need a Stream<String> so you should map before collecting. Something like,


Which outputs


Also, you could generate Stream<Integer> in a number of ways.

        IntStream.range(1, 6).boxed().map(String::valueOf)

Source: stackoverflow