I would like convert a List
without generics to List<MyConcreteType>
.
I also need to filter out only my concrete types.
My current stream logic is like:
List list = new ArrayList();
Object collect1 = list.stream().filter((o -> o instanceof MyConcreteType)).collect(Collectors.toList());
But as a result I'm getting an Object
instead of a List
. Is there a way to convert this Stream
to a List<MyConcreteType>
?
Use parameterized types instead of raw types, and use map
to cast the objects that pass the filter to MyConcreteType
:
List<?> list = new ArrayList();
List<MyConcreteType> collect1 =
list.stream()
.filter((o -> o instanceof MyConcreteType))
.map(s-> (MyConcreteType) s)
.collect(Collectors.toList());
or (similar to what Boris suggested in comment):
List<?> list = new ArrayList();
List<MyConcreteType> collect1 =
list.stream()
.filter(MyConcreteType.class::isInstance)
.map(MyConcreteType.class::cast)
.collect(Collectors.toList());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With