I'm working with a 3d party library, and they return Collections that lack type specifications (e.g. public List getFoo();
) , and I'm trying to convert their return types and return a list with a proper type.
I have created a simple example that demonstrates the problem. e.g.
edit The original question declared l2 as an ArrayList
rather than a List
, that is corrected now.
import java.util.List;
import java.util.ArrayList;
import java.util.stream.Collectors;
public class Foo {
public static void main(String[] args) {
ArrayList l = new ArrayList();
l.add(1);
l.add(2);
List<String> l2 = l.stream().map(Object::toString).collect(Collectors.toList());
}
}
This fails to compile.
$ javac Foo.java
Foo.java:10: error: incompatible types: Object cannot be converted to List<String>
List<String> l2 = l.stream().map(Object::toString).collect(Collectors.toList());
^
1 error
If I modify the program slightly so it compiles and I can check the return type of the stream/collect operation. It "works", although I'd have to cast the result.
e.g.
import java.util.ArrayList;
import java.util.stream.Collectors;
public class Foo {
public static void main(String[] args) {
ArrayList l = new ArrayList();
l.add(1);
l.add(2);
Object l2 = l.stream().map(Object::toString).collect(Collectors.toList());
System.out.println(l2.getClass());
}
}
Running this shows...
$ javac Foo.java
Note: Foo.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
$ java Foo
class java.util.ArrayList
As expected.
So, Collectors.listCollector() does the right thing at runtime, but is this compile time behavior expected? If so, is there a "proper" way around it?
List<Something>
but is returning for some reasonList
?ArrayList
is a list of, useArrayList<?>
, not rawArrayList
. The use of raw types is, in turn, making it harder for the compiler to give you the error message that would have made you say "doh, I get it" --toList()
returns aList
, not anArrayList
. (Also, the problem you had here has nothing whatsoever to do with streams, other than you happened to have used streams -- this is just not understanding the Java type system sufficiently.)