7

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?

fge
  • 119,121
  • 33
  • 254
  • 329

2 Answers2

12

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)

Community
  • 1
  • 1
fge
  • 119,121
  • 33
  • 254
  • 329
0

Due to the fact, ImmutableList implements Collection and Iterable, which are interfaces provided by Java 8, having default implementations for the methods you have enumerated, the answer you gave is not much a surprise, right?

Perhaps the question should be restated as: does ImmutableList implement Collection and Iterable? Because if it does, all default methods provided by Java 8 are usable. In particular: .stream(), .parallelStream() and .spliterator().

But then the answer would require only a lookup into the JavaDoc provided by Guava, which is not a big deal either.

Harmlezz
  • 7,972
  • 27
  • 35
  • Sorry, I don't understand your point at all. Is that _so_ obvious that `Collection` has a default method for `.stream()`? No. I didn't even know it before I checked. – fge Mar 26 '14 at 12:14
  • What is more, this is a good foray into what `default` in interfaces can really do for you; I am sure that when the time comes, Google will override this implementation with a custom one which is faster for these particular `Collection`s. – fge Mar 26 '14 at 12:16