Java Stream How to - Collect List of Integer to a String with separator








Question

We would like to know how to collect List of Integer to a String with separator.

Answer

/*ww  w  . ja  v a  2  s  . c o m*/
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
  public static void main(String[] argv) {
    List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7);

    System.out.println(numbers.stream().map(number -> String.valueOf(number))
        .collect(Collectors.joining(", ")));
  }
}

The code above generates the following result.