Convert a list of integers into a comma-separated string

28,564

Solution 1

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(",")));

Which outputs

1,2,3,4,5

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(","))
);

Solution 2

It is very easy with the Apache Commons Lang library.

Commons Lang

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
String str = org.apache.commons.lang.StringUtils.join(list, ","); // You can use any delimiter
System.out.println(str);  // Output: 1, 2, 3, 4, 5, 6, 7

Java 8 Solution

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
String joinedList = list.stream().map(String::valueOf).collect(Collectors.joining(","));
System.out.println(joinedList);

Solution 3

Using Guava's com.google.common.base.Joiner

String res = Joiner.on(",").join(integerlist);

Using the Java Stream API

String res = integerlist.stream()
                        .map(String::valueOf)
                        .collect(Collectors.joining(","));
Share:
28,564
Nicky
Author by

Nicky

Updated on February 22, 2022

Comments

  • Nicky
    Nicky about 2 years

    I was trying to convert a list of Integers into a 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++) {
        i.add(j);
    }
    System.out.println(i.stream().collect(Collectors.joining(","))); // Line 8
    

    I am getting an error in line number 8.

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

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