Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 convert String of ints to List<Integer>

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?

like image 442
Igor Avatar asked Nov 29 '16 15:11

Igor


3 Answers

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.

like image 67
Tunaki Avatar answered Oct 21 '22 08:10

Tunaki


Regular expression splitting is what you're looking for

Stream.of(ints.split(", "))
      .map(Integer::parseInt)
      .collect(Collectors.toList());
like image 32
Lukas Eder Avatar answered Oct 21 '22 07:10

Lukas Eder


First, split the string into individual numbers, then convert those (still string) to actual integers, and finally collect them in a list. You can do all of this by chaining stream operations.

String ints = "1, 2, 3";
List<Integer> intList = Stream
        .of(ints.split(", "))
        .map(Integer::valueOf)
        .collect(Collectors.toList());
System.out.println(intList);  // [1, 2, 3]
like image 28
tobias_k Avatar answered Oct 21 '22 07:10

tobias_k