Java 8 - Filter list inside map value

Viewed 2495

I am writing a method which takes an input Map of the form Map<Term, List<Integer>> where a Term is defined here.

Method:

  1. Go over the keys of the Map and filter them using a Term attribute.
  2. For each of the remaining keys, get the size of the corresponding list, cap it to 5 (min(List.size(), 5)) and add the output to a global var (say, totalSum)
  3. 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 am unable to take as input a stream of lists, output an integer for each of those lists and return the sum of all the outputs.

I can obviously write it using for loops, but I am trying to learn Java 8 and was curious if this problem is solvable using it.

3 Answers
Related