Igor
Igor

Reputation: 866

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?

Upvotes: 16

Views: 29728

Answers (4)

Tunaki
Tunaki

Reputation: 137064

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.

Upvotes: 28

tl-photography.at
tl-photography.at

Reputation: 125

You can just use the Array function asList, and then convert it the java8 way.

Don't forget to remove the white spaces.

 List<Integer> erg = Arrays.asList(ints.replace(" ", "").split(",")).stream().map(Integer::parseInt).collect(Collectors.toList());

EDIT: Sorry i didn't see that it was a single string, thought it was a array of String.

Upvotes: 2

tobias_k
tobias_k

Reputation: 82899

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]

Upvotes: 3

Lukas Eder
Lukas Eder

Reputation: 220797

Regular expression splitting is what you're looking for

Stream.of(ints.split(", "))
      .map(Integer::parseInt)
      .collect(Collectors.toList());

Upvotes: 24

Related Questions