Igor Igor - 10 days ago 6
Java Question

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?

Answer

Regular expression splitting is what you're looking for

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