如果Map中的所有List值都为空/非空,则使用Streams返回Boolean [英] Use Streams to return Boolean if all the List values in a Map are empty/not-empty

查看:1702
本文介绍了如果Map中的所有List值都为空/非空,则使用Streams返回Boolean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于 Map 将字符串映射到 列表 ,有没有办法使用 Java Streams 返回一个布尔值,其中TRUE表示一个或多个列表有元素?如果地图中的所有列表都为空,则返回FALSE。

Given a Map mapping a String to a List, is there a way to use Java Streams to return a Boolean where TRUE means one or more list had elements? If all lists in the map were empty, return FALSE.

Map< String , List<String> > map = …

可以使用Streams替换这个传统代码吗?

Can use of Streams replace this conventional code?

// See if any diffs were found. Loop through the Map, look at each List of diffs to see if non-empty.
boolean anyElementsInAnyList = false;
for (List<String> list : map.values () ) {
    if (!list.isEmpty()) {
        anyElementsInAnyList = true;
        break;
    }
}

请注意,我们可以在第一次发现。无需检查所有Map值(所有列表)。如果为了效率,Stream可以执行相同的首次停止工作(短路操作),那将是很好的。

Note that we can break out of the examination after the first finding. No need to examine all the Map values (all the Lists). Would be nice if, for efficiency, the Stream could do the same stop-work-on-first-finding (a "short-circuiting" operation).

推荐答案

在Java 8中,您可以检查并非所有列表都是空的。

In Java 8 you can check that not all lists are empty.

 boolean anyNonEmpty = !map.values().stream().allMatch(List::isEmpty);

这篇关于如果Map中的所有List值都为空/非空,则使用Streams返回Boolean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆