Skip to content

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
    .filter(i -> p.matcher(i).find())

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



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

             .map(m ->

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

    return -> p.matcher(input))
                 .filter(matcher -> matcher.find())
                 .map(m ->
                 .mapToInt(s -> Integer.parseInt(s)).sum();