5

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


What's the benefit of using enum embedded inside a class in JAVA?

What's the benefit of using enum embedded inside a class in JAVA? Like so:

public class Outter {
    public enum Color {
        WHITE, BLACK, RED, YELLOW, BLUE
    }
}
4

1 回答 1

6

类型推断是一项新功能。在工具和 IDE 完全开发之前,我建议使用显式类型的 lambda。在某些情况下,如果缺少显式转换,Eclipse 甚至会崩溃,但现在已修复。

这是一个解决方法:

输入“s1”:

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

或使用通用参数:

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

如果您在之前添加参数flatMap而不是map.

但我建议你使用s::concat

asList.stream()
   .flatMap(s -> Arrays.asList("X", "Y").stream().map(s::concat))
   .collect(Collectors.toList());
于 2014-06-16T20:58:12.630 回答