在Java 8 Stream中过滤更多次

时间:2017-05-17 12:27:34

标签: list filter java-8 hashmap java-stream

是否可以在Stream中过滤更多次?例如,如果我有一个带有ID的列表,并且我想要流式传输HashMap并将HashMap的键映射到列表中的键并且它们匹配,我想从HashMap中获取对象并再次对其进行过滤,例如例如,该对象中的int字段大于3,并在最后对它们求和。例如,如果找到10个案例,其中列表的键和HashMap的键是相等的,并且它过滤那10个案例并找到3个案例,例如int字段大于3它返回最后总结这些。

到目前为止,这是我的代码: 当我尝试打印结果列表时,我得到这个:  java.util.stream.ReferencePipeline$2@70177ecd

somemap.entrySet().stream().filter(e -> aListContainingIds.contains(e.getKey()))
            .map(Map.Entry::getValue)
            .map(n -> n.getTheOtherListFromMatchedValue().stream().filter(n -> n.getAnIntFieldFromObject() > 3))
            .collect(Collectors.toList());

1 个答案:

答案 0 :(得分:3)

我认为你应该使用Stream.flatMaptoInt(或Stream.flatMaptoLong)而不只是map

int total = somemap.entrySet().stream()
    .filter(e -> aListContainingIds.contains(e.getKey()))
    .map(Map.Entry::getValue)
    .flatMapToInt(value -> value.getTheOtherListFromMatchedValue().stream()) 
    .filter(n -> n.getAnIntFieldFromObject() > 3)
    .sum();

通常,当您应用的函数返回另一个流时,将使用flatMapToInt(或flatMap如果流元素是某些类的实例而不是基元),并且您需要元素该流的一部分是原始流的一部分。

最后,您可以使用IntStream.sum方法获得总数。