21

I have a list of objects:

List<SomeType> myList;

I want to get a list of sub-types available in this list:

List<SomeChildType> myChildList = myList.stream().filter(e -> e instanceof SomeChildType).collect(??????)

I don't know how to collect to obtain the correct list type.

Thibaut D.
  • 2,521
  • 5
  • 22
  • 33

1 Answers1

78

You need to cast the objects:

List<SomeChildType> myChildList = myList.stream()
                                        .filter(SomeChildType.class::isInstance)
                                        .map(SomeChildType.class::cast)
                                        .collect(toList())
assylias
  • 321,522
  • 82
  • 660
  • 783
  • 11
    I recommend a consistent style. Either `.filter(e -> e instanceof SomeChildType).map(e -> (SomeChildType)e)` or `.filter(SomeChildType.class::isInstance).map(SomeChildType.class::cast)` – Holger Jan 19 '16 at 17:42
  • 1
    @Holger I hadn't thought of `Class::isInstance` - thanks. – assylias Jan 19 '16 at 17:49
  • 1
    `.map(SomeChildType.class::cast)` does not work for me. Any further stream function like `.filter()` wants me to cast the item again and if not the compiler tells me symbol could not be found – xetra11 Jun 06 '17 at 12:42
  • 1
    @xetra11 It compiles fine: http://ideone.com/SBk97H - did you include the static import for `toList`? – assylias Jun 06 '17 at 13:10
  • 1
    This is super extra cool! – GhostCat Aug 23 '17 at 19:24
  • This is a really neat functional solution. Good work. – Scarfe Apr 25 '18 at 08:22
  • In IDEA and Java8, it still prompts me to cast the result to List explicitly, anyone knows why? – K. Symbol Apr 23 '20 at 10:05
  • @K.Symbol I just tested it with intellij and it works as expected. You can maybe create a separate question with your code? – assylias Apr 23 '20 at 12:59
  • @assylias Ok, I have posted my question and screenshot here: https://stackoverflow.com/questions/61453941/need-to-cast-the-list-again-after-already-filtering-and-casting-objects-with-jav – K. Symbol Apr 27 '20 at 07:47
  • We really need a filterMap in java where you provide a lamda that transforms the stream and filters it simultaneously. The signature would be Function> where T is the input and U is the filtered and transformed output. – RedCrafter LP Nov 20 '22 at 09:08