Java 8 Stream String Null Or Empty Filter

前端 未结 6 2067
你的背包
你的背包 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条回答
  •  猫巷女王i
    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)));
    

提交回复
热议问题