Reputation: 13
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.
Upvotes: 1
Views: 708
Reputation: 29038
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()
after replaceAll()
is redundant.collect(Collectors.toList())
with toList()
which is accessible with Java 16 onwards. The difference is that toList()
returns an unmodifiable list and it more performant than collector.Upvotes: 3