Java 8 - 地图值中的过滤器列表

Java 8 - Filter list inside map value

我正在编写一个方法,该方法采用 Map<Term, List<Integer>> 形式的输入 Map,其中定义了 Term here

方法:

  1. 检查 Map 的键并使用 Term 属性过滤它们。
  2. 对于每个剩余的键,获取相应列表的大小,将其限制为 5 (min(List.size(), 5)) 并将输出添加到全局变量(例如,totalSum
  3. Return totalSum

这是我到目前为止写的:

 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();

我无法将列表流作为输入,为每个列表输出一个整数,然后 return 所有输出的总和。

我显然可以使用 for 循环编写它,但我正在尝试学习 Java 8 并且很好奇这个问题是否可以使用它来解决。

您不需要 forEach 方法。您可以 map Map 的每个条目到 intsum 这些整数:

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

forEach 调用终止流。可以不用forEach直接用map。

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));

注意:我是 Eclipse Collections 的提交者。