Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Stream String Null Or Empty Filter

I've got Google Guava inside 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 see there is a statement !String.isNullOrEmpty(entity) inside the filter function.

I don't want to use Guava anymore in the project, so I just want to replace it simply by:

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

How can I do it more elegant?

like image 452
ServerSideCat Avatar asked Jul 13 '15 10:07

ServerSideCat


People also ask

How do I check if a string is empty or null in Java 8?

Using the isEmpty() Method The isEmpty() method returns true or false depending on whether or not our string contains any text. It's easily chainable with a string == null check, and can even differentiate between blank and empty strings: String string = "Hello there"; if (string == null || string. isEmpty() || string.

How do I filter null values in Java 8 stream?

We can use lambda expression str -> str!= null inside stream filter() to filter out null values from a stream.

Can a stream contain null?

Designers of the API did not want to assume whether null means the value is not present (absent value) or is present but equals null. Also, you can still use map(Optional::isNullable) on any stream.


1 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 your filter argument.

like image 59
fge Avatar answered Sep 19 '22 19:09

fge