java集合类 collet,是否有一个Java Stream方法等同于Scala的集合“collect”?

Scala's collection provides a method called collect that merges filter and map into a single method. It's particularly useful when filtering an Object collection to produce a subset of that collection containing only a particular type.

Is there any such thing with Java 8's Stream?

解决方案

Having a combination of filter and map in one step is not that useful in Java given its type system. E.g. there is no such PartialFunction type.

The closest thing is flatMap:

List list=Arrays.asList(0, "foo", 0L, 42.0, true, "false");

List sList = list.stream()

.flatMap(o-> o instanceof String? Stream.of((String)o): Stream.empty())

.collect(Collectors.toList());

System.out.println(sList);

but the expressiveness of

.flatMap(o-> o instanceof String? Stream.of((String)o): Stream.empty())

is not that bigger compared to

.filter(o -> o instanceof String).map(o -> (String)o)

Of course, you may create a helper method encapsulating these steps in a single, undissolvable operation:

static Stream onlyType(Stream> s, Class type) {

return s.filter(type::isInstance).map(type::cast);

}

then you can use it like

List sList=onlyType(list.stream(), String.class).collect(Collectors.toList());

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值