Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

share|improve this question
    
Not for me. It returns Stream<String>. Which compiler are you using? –  Holger Jun 6 at 9:34
    
@Holger, I am compiling inside Eclipse –  Filippo Tabusso Jun 6 at 9:37
    
Well, the Java 8 support of Eclipse is still in development but I suggest you carefully check whether the code you have written inside Eclipse matches what you have written here, before blaming Eclipse as it doesn’t look like a tricky language construct (compiler corner case) to me. With Kepler SR2 and JDT Patch with Java 8 1.0.0.v20140317-1956 it works correctly. –  Holger Jun 6 at 9:41
    
@Holger, you were right about the stream, I have updated my question, apparently the problem is not in the Stream but in the collect which I had initally removed to (over)simplify my question –  Filippo Tabusso Jun 6 at 9:59
    
Ok, now it looks like an Eclipse problem. With Netbeans you can correctly collect into a List<String> –  Holger Jun 6 at 11:34

1 Answer 1

up vote 1 down vote accepted

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());
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.