I'm streaming objects of a class implementing an interface. I'd like to collect them as a list of elements of the interface, rather than the implementing class.
This seems impossible with Java 16.0.1's Stream#toList
method. For example in the code below, the last statement will fail to compile.
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class WhyDodo {
private interface Dodo { }
private static class FancyDodo implements Dodo { }
public static void main(String[] args) {
final List<Dodo> dodos = Stream.of(new FancyDodo()).collect(Collectors.toList());
final List<FancyDodo> fancyDodos = Stream.of(new FancyDodo()).toList();
final List<Dodo> noFancyDodos = Stream.of(new FancyDodo()).toList();
}
}
We could explicitly cast each element from FancyDodo
to Dodo
. But at least for brevity, we could just as well use .collect(Collectors.toList())
.
Why can't I use Stream#toList to collect a list of a class' interface in Java 16?
And if anyone has a better solution than explicitly casting, I'd be happy to hear as well :)