Java Stream collect after flatMap returns List<Object> instead of List<String>

烂漫一生 提交于 2019-12-10 21:14:51

问题


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());

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));

I correctly get a Stream<String>.

Where am I wrong? Can someone help me?

Many thanks in advance.

Edit:

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


回答1:


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.

Here's a workaround:

With a typed "s1":

asList.stream()
   .flatMap(s -> Arrays.asList("X", "Y").stream().map((String s1) -> s + s1))
   .collect(Collectors.toList());

Or with a genric parameter:

asList.stream()
   .flatMap(s -> Arrays.asList("X", "Y").stream().<String>map(s1 -> s + s1))
   .collect(Collectors.toList());

The same is true if you add the parameter before flatMap instead of map.

But I suggest you use s::concat:

asList.stream()
   .flatMap(s -> Arrays.asList("X", "Y").stream().map(s::concat))
   .collect(Collectors.toList());


来源:https://stackoverflow.com/questions/24078414/java-stream-collect-after-flatmap-returns-listobject-instead-of-liststring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!