Skip to content
Advertisement

Java 8 convert for loop and summing of values to stream/lambda?

I have some String inputs that I am looping over that I am trying to convert to java 8 stream/lambdas but was having some issues. My boilerplate code looks like this:

public static int count(List<String> list) {
    String regex = "someRegexPatternHere"
    Pattern p = Pattern.compile(regex);
    int sum = 0;

    for (String val: list) {
        Matcher m = p.matcher(val);
        if (m.find()) {
            // summing logic here 
        }
    }
    return sum;
}

I was trying to do something like

list.stream()
    .filter(i -> p.matcher(i).find())
    .map(..............)
    ...

… but couldn’t get the summ’ing logic down. could anyone point me in the right direction?

Advertisement

Answer

You need to apply first the matcher then filter on the find

return inputs.stream()
             .map(p::matcher)
             .filter(Matcher::find)
             .map(m -> m.group(0))
             .mapToInt(Integer::parseInt)
             .sum();

It could more clear for you to see it using lambda function but that’s the same

    return inputs.stream().map(input -> p.matcher(input))
                 .filter(matcher -> matcher.find())
                 .map(m -> m.group(0))
                 .mapToInt(s -> Integer.parseInt(s)).sum();
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement