I am trying to convert a List<String>
to List<Integer>
by using Java 8 streams. However, there are a few invalid integers in the List<String>
. How to extract the integer values only and then convert the String
list to Integer
list?
For example:
List<Integer> intList = new ArrayList<Integer>();
List<String> strList = new ArrayList<String>();
String str[] = {"464 mm", "80 mm", "1000", "1220", "48 mm", "1020"};
strList = Arrays.asList(str);
intList.addAll(strList.stream().map(Integer::valueOf).collect(Collectors.toList()));
I am getting error java.lang.NumberFormatException: For input string: "464 mm"
.
Is there a way, I can use regex
str.replaceAll("[^\d]", " ").trim()
to extract the numbers and then convert. I dont want to use a for loop or while loop as this may hamper my code performance.
CodePudding user response:
In order to remove all non-numeric characters from each string, you need to apply map()
before converting the stream of String
into stream of Integer
.
List<Integer> nums =
strList.stream()
.map(s -> s.replaceAll("[^\\d]", ""))
.map(Integer::valueOf)
.collect(Collectors.toList());
System.out.println(nums);
Output for input {"464 mm", "80 mm", "1000", "1220", "48 mm", "1020"}
[464, 80, 1000, 1220, 48, 1020]
Note:
trim()
afterreplaceAll()
is redundant.- Since you are adding all the contents of the list generated by the stream pipeline into another list, you might substitute
collect(Collectors.toList())
withtoList()
which is accessible with Java 16 onwards. The difference is thattoList()
returns an unmodifiable list and it more performant than collector. - Iterative solutions almost always perform better than stream-based. Lambdas and streams were introduced in Java to provide a way of organizing the code that more readable and concise.