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

流过昼夜 提交于 2019-12-03 14:38:52

问题


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 = …

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

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


回答1:


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

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



回答2:


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

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



回答3:


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 .



来源:https://stackoverflow.com/questions/35282418/use-streams-to-return-boolean-if-all-the-list-values-in-a-map-are-empty-not-empt

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!