Java Stream在flatMap之后收集List< Object>而不是List< String> [英] Java Stream collect after flatMap returns List<Object> instead of List<String>
问题描述
我使用Java 8流尝试以下代码:
I tried the following code using Java 8 streams:
Arrays.asList("A", "B").stream()
.flatMap(s -> Arrays.asList("X", "Y").stream().map(s1 -> s + s1)).collect(Collectors.toList());
我得到的是一个列表< Object>
而我希望一个 List< String>
。如果我删除收集,我尝试:
What I get is a List<Object>
while I would expect a List<String>
. If I remove the collect and I try:
Arrays.asList("A", "B").stream().flatMap(s -> Arrays.asList("X", "Y").stream().map(s1 -> s + s1));
我正确地获取了一个 Stream< String>
。
I correctly get a Stream<String>
.
我错了哪里?有人能帮我吗?
Where am I wrong? Can someone help me?
非常感谢提前。
编辑:
问题是由于Eclipse(现在使用Kepler SR2与java 8补丁1.0.0.v20140317-1956)。如果使用javac进行编译,或者如Holger所说,使用Netbeans
The problem is due to Eclipse (now using Kepler SR2 with java 8 patch 1.0.0.v20140317-1956). The problem does non appear if compiling using javac or, as commented by Holger, using Netbeans
推荐答案
类型推断是一个新功能,则不会出现此问题。在工具和IDE完全开发之前,我建议使用显式类型的lambdas。如果缺少明确的转换,那么Eclipse甚至会崩溃,但是现在已经修复了。
Type inference is a new feature. Until tools and IDEs are fully developed I recommend using explicitly typed lambdas. There ware cases where Eclipse even crashed if an explicit cast was missing, but that is fixed now.
这是一个解决方法:
使用一个类型s1:
asList.stream()
.flatMap(s -> Arrays.asList("X", "Y").stream().map((String s1) -> s + s1))
.collect(Collectors.toList());
或使用genric参数:
Or with a genric parameter:
asList.stream()
.flatMap(s -> Arrays.asList("X", "Y").stream().<String>map(s1 -> s + s1))
.collect(Collectors.toList());
如果在 flatMap $ c之前添加参数也是如此$ c>而不是
map
。
但是我建议你使用 s :: concat
:
asList.stream()
.flatMap(s -> Arrays.asList("X", "Y").stream().map(s::concat))
.collect(Collectors.toList());
这篇关于Java Stream在flatMap之后收集List< Object>而不是List< String>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!