java返回值只有一个吗,Java 8 Spliterator(或类似的),如果只有一个值,则返回值...

I'm a big fan of the singleOrEmpty stream operator. It's not in the std lib, but I find it very useful. If a stream has only a single value, it returns that value in an Optional. If it has no values or more than one value, it returns Optional.empty().

Optional value = someList.stream().{singleOrEmpty}

[] -> Optional.empty()

[1] -> Optional.of(1)

[1, 1] -> Optional.empty()

etc.

public static Optional singleOrEmpty(Stream stream) {

return stream.limit(2)

.map(Optional::ofNullable)

.reduce(Optional.empty(),

(a, b) -> a.isPresent() ^ b.isPresent() ? b : Optional.empty());

}

The only problem is, you have to put it at the beginning of your call

singleOrEmpty(someList.stream().filter(...).map(...))

rather than sequentially at the end

someList.stream().filter().map().singleOrEmpty()

which makes it harder to read than other stream mechanisms.

So as a newbie to this stream processing stuff, does anybody have any tricks for how to go about putting a short-circuiting singleOrEmpty mechanism at the end of a sequence of stream transformations?

解决方案

It will not be as fast as the one with limit(2) but you can use it as list.stream().filter(...).map(...).collect(singleOrEmpty())

static Collector> singleOrEmpty() {

return Collectors.collectingAndThen(

Collectors.mapping(

Optional::of,

Collectors.reducing((a, b) -> Optional.empty())

),

o -> o.orElseGet(Optional::empty)

);

}

Stream.empty().collect(singleOrEmpty()); // Optional.empty

Stream.of(1).collect(singleOrEmpty()); // Optional[1]

Stream.of(1, 1).collect(singleOrEmpty()); // Optional.empty

Stream.of(1, 1).skip(1).collect(singleOrEmpty()); // Optional[1]

For what it's worth, unless this is really performance critical code, I would personally prefer the less clever but much clearer implementation

static Collector> singleOrEmpty() {

return Collectors.collectingAndThen(

Collectors.toList(),

lst -> lst.size() == 1

? Optional.of(lst.get(0))

: Optional.empty()

);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值