user1283068 user1283068 - 7 months ago 11
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};
Arrays.stream(la).map(Long::valueOf).collect(Collectors.toSet());


When this does:

String la[] = new String[] {"1","2","3"};
Arrays.stream(la).map(Long::valueOf).collect(Collectors.toSet());


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

Arrays.stream(la) 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 = Arrays.stream(la).mapToObj(Long::valueOf).collect(Collectors.toSet());

Your second snippet works since here Arrays.stream 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.

Comments