Java 如果 Map 中的所有 List 值都为空/非空,则使用 Streams 返回布尔值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35282418/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 16:29:40  来源:igfitidea点击:

Use Streams to return Boolean if all the List values in a Map are empty/not-empty

javajava-stream

提问by Basil Bourque

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

给定一个MapString 到 a的映射List,有没有一种方法可以使用Java Streams返回一个布尔值,其中 TRUE 表示一个或多个列表具有元素?如果地图中的所有列表都为空,则返回 FALSE。

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

Can use of Streams replace this conventional code?

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

// 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;
    }
}

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

请注意,我们可以在第一次发现后退出检查。无需检查所有 Map 值(所有列表)。如果为了效率,Stream 可以执行相同的 stop-work-on-first-finding(“短路”操作),那就太好了。

采纳答案by Peter Lawrey

Stream::allMatch

Stream::allMatch

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

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

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

Notice that Stream::allMatchis a short-circuiting terminal operation. So the stream is efficient, not running any longer than need be.

请注意,这Stream::allMatch是一个短路端子操作。所以流是高效的,运行时间不会超过需要。

回答by rgettman

Use the anyMatchmethodthat finds if any element of the stream matches a Predicate. Here, your predicate is that the entry's value (the list) is not empty.

使用anyMatch方法是,如果认定该流的任何元素相匹配的Predicate。在这里,您的谓词是条目的值(列表)不为空。

boolean anyNonEmpty = map.entrySet()
    .stream()
    .anyMatch(entry -> !entry.getValue().isEmpty());

回答by Akhil

int size = Map.entrySet().stream()
                           .map(entry -> entry.getValue())
                           .flatMap(list -> list.stream())
                           .size();
if(size==0)
  return Boolean.False;
else
  return Boolean.True;

This code is a simple one this may help for your work .

此代码很简单,可能对您的工作有所帮助。