/java/

Java8 – Lambda & Predicate

2015-01-06 21:23:58

This post is continuation of http://www.blog.btbw.pl/java/java8-lambda-simple-use-case/

In Previs version

we have interface and base on it we prepared filter mechanism based on lambda

public interface AnimalFilter {
    public boolean check(Animal animal);
}
private static void log(Animal animal, AnimalFilter filter) {
    if (filter.check(animal)) {
        // log this ...
        System.out.println("LOG: " + animal.getName());
    }
}
for (Animal animal : animals) {
    log(animal, (Animal a) -> a.getSex().equals(Animal.SEX.FEMALE));
    log(animal, (Animal a) -> a.getColor().equals(Animal.COLOR.BROWN));
}

quite nice but this is not the best version

Predicate & forEach

we can abandon old "for" and extra "interface" and use somthink new

instead of "for" we can use "forEach"

List

<animal> animals = NoeShip.getAnimals();
animals.forEach((a) -&gt; System.out.println(a.getName()));

instead of custom AnimalFilter interface we can use Predicate

Predicate<animal> filter1 = animal -&gt; Animal.SEX.MEN.equals(animal.getSex());
Predicate<animal> filter2 = animal -&gt; Animal.SEX.FEMALE.equals(animal.getSex());
Predicate<animal> filter3 = animal -&gt; "dog".equals(animal.getSpecies());

how to use it? check it out:

animals.stream()
        .filter(filter1)
        .forEach((animal) -&gt; System.out.println(animal.getName()));

animals.stream()
        .filter(filter1.or(filter2))
        .forEach((animal) -&gt; System.out.println(animal.getName()));

animals.stream()
        .filter(filter1.and(filter3))
        .forEach((animal) -&gt; System.out.println(animal.getName()));