Java 8 convert String of ints to List<Integer>

Igor picture Igor · Nov 29, 2016 · Viewed 22k times · Source

I have a String:

String ints = "1, 2, 3";

I would like to convert it to a list of ints:

List<Integer> intList

I am able to convert it to a list of strings this way:

List<String> list = Stream.of("1, 2, 3").collect(Collectors.toList());

But not to list of ints.

Any ideas?

Answer

Tunaki picture Tunaki · Nov 29, 2016

You need to split the string and make a Stream out of each parts. The method splitAsStream(input) does exactly that:

Pattern pattern = Pattern.compile(", ");
List<Integer> list = pattern.splitAsStream(ints)
                            .map(Integer::valueOf)
                            .collect(Collectors.toList());

It returns a Stream<String> of the part of the input string, that you can later map to an Integer and collect into a list.

Note that you may want to store the pattern in a constant, and reuse it each time it is needed.