任何人都可以向我解释为什么以下不起作用:
long la[] = new long[] {1,2,3}; Arrays.stream(la).map(Long::valueOf).collect(Collectors.toSet());这样做:
String la[] = new String[] {"1","2","3"}; Arrays.stream(la).map(Long::valueOf).collect(Collectors.toSet());前者给出了编译错误,而后者没有。 编译错误是如此神秘(Eclipse),我无法理解它。
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.
最满意答案
Arrays.stream(la)执行生成public static LongStream stream(long[] array)的方法public static LongStream stream(long[] array) 。 LongStream的map方法返回一个LongStream (即源LongStream每个long元素都映射到目标LongStream的long元素)。 LongStream没有接受单个参数的collect方法,这就是collect(Collectors.toSet())不通过编译的原因。
如果你使用mapToObj它应该工作:
Set<Long> set = Arrays.stream(la).mapToObj(Long::valueOf).collect(Collectors.toSet());你的第二个代码片段起作用,因为Arrays.stream产生一个引用类型的Stream<String> ( Stream<String> ),其map方法产生另一个引用类型的Stream<Long> (在你的情况下为Stream<Long> )。 这里, Stream有一个接受单个参数的collect方法 - collect(Collector<? super T, A, R> collector) - 所以collect(Collectors.toSet())可以工作。
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.
更多推荐
发布评论