Java 8 – filter lists in map values

I am writing a method that uses the input map in the format of map < term, list < integer > > One of the terms is defined as here

method:

>Browse the map keys and filter them using the term attribute. > For each remaining key, get the size of the corresponding list, limit it to 5 (min (list. Size(), 5)) and add the output to the global variable (for example, totalsum) > return totalsum

This is what I have written so far:

inputMap
    .entrySet()
    .stream()
    .filter(entry -> entry.getKey().field().equals(fieldName))    // Keep only terms with fieldName
    .forEach(entry -> entry.getValue()
        .map(size -> Math.min(entry.getValue().size(),5)))   // These 2 lines do not work
        .sum();

I can't take a list stream as input, output an integer for each list and return the sum of all outputs

I can obviously use the for loop to write it, but I'm trying to learn java 8 and wonder if it can solve this problem

Solution

You do not need the foreach method You can map each entry in the map to an int and sum these integers:

int sum = inputMap
    .entrySet()
    .stream()
    .filter(entry -> entry.getKey().field().equals(fieldName))
    .mapToInt(entry -> Math.min(entry.getValue().size(),5))
    .sum();
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>