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

前端 未结 3 1801
生来不讨喜
生来不讨喜 2020-12-28 13:16

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 e

相关标签:
3条回答
  • 2020-12-28 13:43
    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 .

    0 讨论(0)
  • 2020-12-28 13:47

    Stream::allMatch

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

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

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

    0 讨论(0)
  • 2020-12-28 13:59

    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());
    
    0 讨论(0)
提交回复
热议问题