Java 8流和简单类型(Java 8 streams and simple types)

编程入门 行业动态 更新时间:2024-10-27 22:34:59
Java 8流和简单类型(Java 8 streams and simple types)

任何人都可以向我解释为什么以下不起作用:

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.

更多推荐

本文发布于:2023-08-07 08:03:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1462003.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型   简单   Java   types   simple

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!