Java 8 Stream String Null or Empty Filter

I have guava in the stream:

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

As you can see, inside the filter function there is an operator !String.isNullOrEmpty(entity) .

I no longer want to use Guava in the project, so I just want to replace it simply:

 string == null || string.length() == 0; 

How can I make it more elegant?

+18
java guava java-8 java-stream
source share
6 answers

You can write your own predicate:

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

Then just use valueNotNullOrEmpty as the filter argument.

+18
source share

If you prefer to use commons-lang3, StringUtils has

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

These methods can be used in filters as references to methods:

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

or like lambdas:

 this.stringList.stream().filter(s -> StringUtils.isNotBlank(s)); 
+14
source share

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 mentioned, you cannot use this on Map.Entry<?,?> ...

+7
source share

You can break the filter into two stages:

 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 the side of the note, most implementations of Map.Entry.toString() do exactly what you do in map() , so theoretically you could just do map(Map.Entry::toString) . But I would not rely on this if you do not create toString() or something that does not require documented or deterministic behavior.

In addition, I know that you want to abandon Guava, but here is a solution that might make you reconsider:

 Joiner.on(',').withKeyValueSeparator("=") .join(Maps.filterValues(map, Predicates.not(Strings::isNullOrEmpty))); 
+2
source share

Java 11 has a new Predicate :: not method.

This way you can filter the empty string:

 list.stream() .filter(Objects::nonNull) .filter(Predicate.not(String::isEmpty)) 
+1
source share

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

0
source share

All Articles