16

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?

1
  • 4
    Your last line of code will give you a list with exactly one string it, with the value "1, 2, 3". Did you mean: Stream.of("1", "2", "3")? Commented Nov 29, 2016 at 15:43

4 Answers 4

28

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.

Sign up to request clarification or add additional context in comments.

3 Comments

@Igor There is no winner really, just different solutions to do the task. Creating an array and passing it to Stream.of works as well, and depending on the strings you want to parse, and the exact delimiter (if it isn't ", "), maybe this solution with splitAsStream will be faster than the other. This needs to be measured.
I'd prefer this one over mine. Wasn't aware of the Pattern.splitAsStream() method. Excellent!
You can use Pattern.compile(", ", Pattern.LITERAL); to hint to the engine that there is no real pattern matching. Of course, the engine will find out itself without the flag, but specifying the flag skips the process of analyzing the pattern.
24

Regular expression splitting is what you're looking for

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

5 Comments

Yes, but he specifically asked for Java8 way to solve this
This won´t create a List<Integer>
I always recommend to use Arrays.stream if the input is an array, i.e. when there is not a real varargs invocation. This makes it clear that we stream over an array and will work correctly for arrays of primitive types instead of creating a single element stream. For this specific case, both will do the same.
@Holger: Yeah, that's not a bad idea, although some APIs that used to take array arguments now take varargs arguments since Java 5, so, this distinction might not be eternal...
There was a retrofitting when varargs were introduced with Java 5, but that’s not something to happen again very often. And, making Arrays.asList a varargs method has been considered a design mistake, as it contradicts the purpose of creating a wrapper around an existing array (e.g. the array can be modified through the returned List). Java 9 is going to fix that. There, you can use List.of(…) to create an immutable list of arbitrary size (true varargs semantics) and Arrays.asList(array) to wrap an array in a mutable List (still being varargs due to compatibility constraints).
3

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]

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.