I\'ve got Google Guava inside Stream:
this.map.entrySet().stream()
.filter(entity -> !Strings.isNullOrEmpty(entity.getValue()))
.map(obj -> String.form
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))
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));
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.
It works for me: list.stream().filter(el-> el != null && !el.toString().trim().isEmpty()).collect(Collectors.toList());
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<?,?>
...
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)));