任何人都可以向我解释为什么以下内容不起作用:
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),我无法理解它。
最佳答案
Arrays.stream(la)
执行方法 public static LongStream stream(long[] array)
产生 LongStream
. LongStream
的 map
方法返回 LongStream
(即源 long
的每个 LongStream
元素映射到目标 long
中的 LongStream
元素)。 LongStream
没有 collect
接受单个参数的方法,这就是为什么 collect(Collectors.toSet())
没有通过编译。
如果你使用 mapToObj
它应该可以工作:
Set<Long> set = Arrays.stream(la).mapToObj(Long::valueOf).collect(Collectors.toSet());
你的第二个代码片段从这里开始有效 Arrays.stream
产生 Stream
引用类型 ( Stream<String>
) 的 map
方法产生另一个 Stream
引用类型(在您的情况下为 Stream<Long>
)。在这里,Stream
有一个 collect
接受单个参数的方法 - collect(Collector<? super T, A, R> collector)
- 所以 collect(Collectors.toSet())
有效。
关于Java 8 流和简单类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36769700/