Use Case
I'm using an 3rd party library where there are two very similar classes that don't implement an interface. The code currently loops through a list of items to find the first occurrence of an object using one of these classes and then converts it to a stream where it is processed. It would be nice if I could convert this code to use a stream and have it chained to the rest of my code.
Current Code
for (Component3Choice component: components) {
if (component instanceof OptionalComponent3Bean) {
OptionalComponent3Bean section = (OptionalComponent3Bean) component;
entryStream = section.getSection().getEntry().stream()
break;
}
else if (component instanceof RequiredComponent3Bean) {
RequiredComponent3Bean section = (RequiredComponent3Bean) component;
entryStream = section.getSection().getEntry().stream();
break;
}
}
... do something with the stream ...
Desired Code
components.stream()
.filter(entry -> entry instanceof OptionalComponent3Bean
|| entry instanceof RequiredComponent3Bean)
.findFirst()
.map( {{ cast entry }} )
.map( castedEntry.getSection().getEntry())
... continue on with my processing
Question
Is it possible cast the entry based on the previous filter in the stream?
Component3Choicedefine a methodgetSection()?OptionalComponent3Bean&RequiredComponent3Beanto implement an interface (for instanceHasSection) which would definegetSection()?