While refactoring some code I came across this piece of code
class MyClassB extends MyClassA {...}
// other classes extending from MyClassA
...
List<MyClassA> list = new ArrayList<>();
// fill list
list.stream()
.filter(o -> o instanceof MyClassB)
.map(o -> (MyClassB)o)
.forEach(/* do something */)
The actual piece of code was a lot bigger, but since I like to use method references where possible, I refactored the stream into this:
list.stream()
.filter(MyClassB.class::isInstance)
.map(MyClassB.class::cast)
.forEach(/* do something */)
I am now wondering if this is in any way more efficient? More advisable? I think that Java generates less code using method references but could there be other negative implications I'm not thinking of since checking for instanceOf and casting are rather internal processes?
In my opinion it will still be as readable as before. Any thoughts are most welcome.