guava 依赖java8,我使用Guava的不可变集合(为Java 6编译)和一个Java 8 JRE,我可以使用新的流接口吗?...

I use Guava and in particular their immutable collections (ImmutableList, ImmutableSet).

But Guava is compiled for Java 6. If I use Java 8, can I use .stream() with them?

解决方案

Yes you can.

The .stream() method, which is defined in the Collection interface, has a default implementation. And so do, for that matter, .parallelStream() and .spliterator(). And both Lists and Sets "are" Collections.

And it doesn't end there since you can also use Map's .forEach() on Guava's ImmutableMaps as well. Map does have other default operations, but they mutate the map, and Guava's immutable collections/maps are... Well...

Note that more generally, each time an interface's method has a default implementation, it will be mentioned in the javadoc, since the method's return type will be preceded with the default keyword.

Some sample, very crude code which works and makes use of that (along with the concept of Single Abstract Method used in lambdas, see here for more details):

ImmutableSet.of(23, 2389, 19).stream().forEach(System.out::println);

(System.out is a PrintStream, and its .println() method signature is the same as that of a Consumer)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值