java return null,how to return null when list is empty in java 8

可以将文章内容翻译成中文,广告屏蔽插件会导致该功能失效:

问题:

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 + ")";

})

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值