user1283068 user1283068 - 1 year ago 50
Java Question

Java 8 streams and simple types

Can anyone explain to me why the following does not work:

long la[] = new long[] {1,2,3};;

When this does:

String la[] = new String[] {"1","2","3"};;

The former gives a compilation error while the latter does not. The compilation error is so cryptic (Eclipse) that I cannot make sense of it.

Answer executes the method public static LongStream stream(long[] array) which produces a LongStream. LongStream's map method returns a LongStream (i.e. each long element of the source LongStream is mapped to a long element in the target LongStream). LongStream doesn't have a collect method that accepts a single argument, which is why collect(Collectors.toSet()) doesn't pass compilation.

It should work if you use mapToObj :

Set<Long> set =;

Your second snippet works since here produces a Stream of a reference type (Stream<String>) whose map method produces another Stream of a reference type (Stream<Long> in your case). Here, Stream has a collect method that accepts a single argument - collect(Collector<? super T, A, R> collector) - so collect(Collectors.toSet()) works.