Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert list without generics to list with generics using streams in java?

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>?

like image 909
pixel Avatar asked Jan 04 '23 01:01

pixel


1 Answers

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());
like image 129
Eran Avatar answered Jan 05 '23 14:01

Eran