Lets say I have Animal object and successors. One of them is Dog and only he implements
public interface Barkable{
Bark getBark();
}
Now, I have
List<Animal> animals
Which holds all animal types and I want to collect all instances of Bark
(which only exists in Dog).
I can do it Java 7 style
ArrayList<Bark> barks = new ArrayList<>();
for (Animal animal : AnimalsList) {
if (animal instanceof Barkable){
barks.add((Barkablle) dog).getBark();
}
}
How do I do it in Java 8 streams?
Will it be as fast as the java-8 version?
You can use filter()
to get the Barkable
instances and then use map
to get the Bark
s :
List<Bark> barks = AnimalsList.stream()
.filter (a -> a instanceof Barkable)
.map (a -> ((Barkable) a).getBark())
.collect (Collectors.toList());
As for the running time, you'll have to test for yourself. It will depend on the size of the input list, and you may be able to make it run faster by using parallelStream()
instead of stream()
(if your input is large enough for a parallel stream to make a difference).
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments