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?
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.
We can use lambda expression str -> str!= null inside stream filter() to filter out null values from a stream.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With