Suppose that I have a list:
List<String> dest = Arrays.asList(
"abc abd 2000",
"idf owe 1200",
"jks ldg 789",
"ccc hhh 2000",
"www uuu 1000"
);
and I’m trying to get the number at the end of every string. The given list has only integers in it, but I’m writing the regex for doubles too:(\\d+\\.?\\d+). In Java 1.8, I wrote the following code:
ArrayList<String> mylist = new ArrayList<>(
dest.stream()
.filter(Pattern.compile("\\D+\\s\\D+\\s(\\d+\\.?\\d+)").asPredicate())
.collect(Collectors.toList())
);
What I’m trying to do is – get the (\\d+\\.?\\d+) group from each found string, how can I do it? I was thinking about applying a Matcher to each element of the list but I’m not sure about how to implement it.
>Solution :
filter keeps or removes elements from the list. If you want to transform stream elements (which you do when you extract the number), use map.
Then you can use the regex (along with a Matcher) to extract data:
Pattern p = Pattern.compile("\\D+\\s\\D+\\s(\\d+\\.?\\d+)");
List<String> mylist = dest.stream()
.map(s -> {
Matcher matcher = p.matcher(s);
matcher.find();
return matcher.group(1); //error handling sold seperately
})
.collect(Collectors.toList());
System.out.println(mylist);
prints
[2000, 1200, 789, 2000, 1000]