Returns false if any of the values ​​on the map is an empty string or just spaces in java8

I am trying to write a one-line code that will return false if any of the values ​​on the map are an empty string or a string of spaces. Thoughts?

Something like an extended version:

 Optional.ofNullable(map).filter(s -> s.isEmpty());
+4
source share
3 answers

using your current approach:

boolean present = 
        Optional.ofNullable(map)
                .filter(x -> 
                        x.values().stream()
                                  .noneMatch(s -> s != null && s.trim().isEmpty()))
                                  .isPresent();

or simply:

boolean present = map != null && 
                  map.values()
                     .stream()
                     .noneMatch(s -> s != null && s.trim().isEmpty());
+4
source

What about:

return map.values().stream().noneMatch(v -> v != null && v.trim().isEmpty());

v.trim().isEmpty()true if the string is empty ( "") or contains only spaces.

noneMatchtrue if no elements in the stream (values ​​here) satisfy the predicate. This is a short circuit, so it is good and effective.

+3
source

,

public static boolean containsNoEmptyString(Map<?,?> map) {
    return !map.containsValue("");
}

,

public static boolean containsNoBlankString(Map<?,String> map) {
    return map.values().stream().noneMatch(Pattern.compile("^\\s*$").asPredicate());
}

, s.trim().isEmpty(), , , . , .. , trim() , , .

, trim() . , , , trim() .

, , , . trim() , , . , , , .

, . , . trim() , , . , , . , , , .

+3

Source: https://habr.com/ru/post/1692067/


All Articles