简体   繁体   中英

Java 8 - Filter list inside map value

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.

You don't need the forEach method. You can map each entry of the Map to an int , and sum those integers :

int sum = inputMap
    .entrySet()
    .stream()
    .filter(entry -> entry.getKey().field().equals(fieldName))
    .mapToInt(entry -> Math.min(entry.getValue().size(), 5))
    .sum();

With Eclipse Collections , the following will work using MutableMap and IntList .

MutableMap<Term, IntList> inputMap =
    Maps.mutable.of(term1, IntLists.mutable.of(1, 2, 3), 
                    term2, IntLists.mutable.of(4, 5, 6, 7));

long sum = inputMap
    .select((term, intList) -> term.field().equals(fieldName))
    .sumOfInt(intList -> Math.min(intList.size(), 5));

Note: I am a committer for Eclipse Collections.

The forEach invocation terminates the stream. You can use map directly without forEach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM