可以将文章内容翻译成中文,广告屏蔽插件会导致该功能失效:
问题:
how can i change this method so that it returns null if list passed as parameter isEmpty ? (without using a if)
default String getFiltersExpression(List filters) {
return Optional.ofNullable(filters)
.map(Collection::stream)
.orElseGet(Stream::empty)
.map(WorkListViewMapper::formatValue)
.map(f -> f.getCriteria() + f.getOperator() + f.getValue())
.collect(Collectors.joining(" AND ", "(", ")"));
}
回答1:
I would recommend not returning null and rather returning a "()" string as the filter expression for this you can just append a filter for an empty list there as :
String getFiltersExpression(List filters) {
return Optional.ofNullable(filters)
.filter(l -> !l.isEmpty())
.map(Collection::stream)
.orElseGet(Stream::empty)
.map(WorkListViewMapper::formatValue)
.map(f -> f.getCriteria() + f.getOperator())
.collect(Collectors.joining(" AND ", "(", ")"));
}
Using Java-9 syntax :
String getFiltersExpressions(List filters) {
return Stream.ofNullable(filters)
.flatMap(Collection::stream)
.map(WorkListViewMapper::formatValue)
.map(f -> f.getCriteria() + f.getOperator() + f.getValue())
.collect(Collectors.joining(" AND ", "(", ")"));
}
回答2:
An alternative way is to start streaming only if the list is non null and non empty:
default String getFiltersExpression(List filters) {
return Optional.ofNullable(filters)
.filter(fs -> !fs.isEmpty())
.map(fs -> fs.stream()
.map(WorkListViewMapper::formatValue)
.map(f -> f.getCriteria() + f.getOperator() + f.getValue())
.collect(Collectors.joining(" AND ", "(", ")")))
.orElse(null);
}
Then you get null instead of ().
回答3:
.collect(
Collectors.collectingAndThen(
Collectors.joining(),
str->{
if(str.isEmpty()) return null;
return str;
}
)
);
Given OP's joining statement, Collectors.joining(" AND ", "(", ")") we could modify the above.
Collectors.collectingAndThen(
Collectors.joining(" AND "),
str->{
if(str.isEmpty()) return null;
return "(" + str + ")";
})