Lets say I have
class Dog extends Animal {}
class Cat extends Animal {}
And I have a list of Animals Using Guava FluentIterable I can filter and convert in one step
List<Cat> cats = FluentIterable.from(animals)
.filter(Cat.class)
.toList();
Using Java8 I need to do
List<Cat> cats = animals.stream()
.filter(c -> c instanceof Cat)
.map(c -> (Cat) c)
.collect(Collectors.toList());
There is no way I can make the filter & map in one step, right?
The map
step is unnecessary at runtime (it simply does nothing), you need it just to bypass the type checking during the compilation. Alternatively you can use dirty unchecked cast:
List<Cat> cats = ((Stream<Cat>) (Stream<?>) animals.stream().filter(
c -> c instanceof Cat)).collect(Collectors.toList());
Unfortunately there's no standard way to do this in single step, but you may use third-party libraries. For example, in my StreamEx
library there's a select
method which solves this problem:
List<Cat> cats = StreamEx.of(animals).select(Cat.class).toList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With