Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I use Guava's immutable collections (compiled for Java 6) and a Java 8 JRE, can I use the new stream interface?

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?

like image 722
fge Avatar asked Mar 26 '14 11:03

fge


1 Answers

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)

like image 113
fge Avatar answered Nov 12 '22 01:11

fge