4

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

3
  • Just cast it List<MyConcreteType> typedList = (List<MyConcreteType>) list. Commented Dec 19, 2017 at 13:34
  • @BoristheSpider but I need to filter it first - cause it can contain other items as well Commented Dec 19, 2017 at 13:35
  • 4
    list.stream().filter(MyConcreteType.class::isInstance).map(MyConcreteType.class::cast).collect(Collectors.toList()) then Commented Dec 19, 2017 at 13:36

1 Answer 1

10

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());
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.