Java 8 Stream String Null Or Empty Filter

前端 未结 6 2033
你的背包
你的背包 2021-01-01 09:34

I\'ve got Google Guava inside Stream:

this.map.entrySet().stream()
.filter(entity -> !Strings.isNullOrEmpty(entity.getValue()))
.map(obj -> String.form         


        
相关标签:
6条回答
  • 2021-01-01 10:16

    In java 11 there is a new method Predicate::not.

    So you can filter out empty string :

    list.stream()
      .filter(Objects::nonNull)
      .filter(Predicate.not(String::isEmpty))
    
    0 讨论(0)
  • 2021-01-01 10:23

    If you prefer to use commons-lang3, StringUtils has

    • isEmpty()
    • isNotEmpty()
    • isBlank()
    • isNotBlank()

    These methods can be used in filters as method references:

    this.stringList.stream().filter(StringUtils::isNotBlank);
    

    or as lambdas:

    this.stringList.stream().filter(s -> StringUtils.isNotBlank(s));
    
    0 讨论(0)
  • 2021-01-01 10:28

    You can write your own predicate:

    final Predicate<Map.Entry<?, String>> valueNotNullOrEmpty
        = e -> e.getValue() != null && !e.getValue().isEmpty();
    

    Then just use valueNotNullOrEmpty as your filter argument.

    0 讨论(0)
  • 2021-01-01 10:31

    It works for me: list.stream().filter(el-> el != null && !el.toString().trim().isEmpty()).collect(Collectors.toList());

    0 讨论(0)
  • 2021-01-01 10:32

    You can create your own Strings class with your own predicate:

    public class Strings {
      public static boolean isNotNullOrEmpty (String str) {
        return str != null && !str.isEmpty();
      }
    }
    

    Then in your code:

    .filter(Strings::isNotNullOrEmpty)
    

    But as @fge mentionned, you can't use that on a Map.Entry<?,?>...

    0 讨论(0)
  • 2021-01-01 10:35

    You can break down the filter into two steps:

    this.map.entrySet().stream()
        .filter(entity -> entity.getValue() != null)
        .filter(entity -> !entity.getValue().isEmpty())
        .map(obj -> String.format("%s=%s", obj.getKey(), obj.getValue()))
        .collect(Collectors.joining(","))
    

    On a side note, most Map.Entry.toString() implementations do exactly what you're doing in map(), so you could theoretically just do map(Map.Entry::toString). But I wouldn't rely on that unless you're producing a toString() or something that doesn't require documented or deterministic behavior.

    Also, I know you want to abandon Guava, but here's a solution that might make you reconsider:

    Joiner.on(',').withKeyValueSeparator("=")
          .join(Maps.filterValues(map, Predicates.not(Strings::isNullOrEmpty)));
    
    0 讨论(0)
提交回复
热议问题