/java/

Java8 – Lambda simple use case

2015-01-05 22:40:09

First we have to preper some data for our example

public class Animal {

    public enum COLOR {WHITE, YELLOW, RED, BROWN, GREY, BLACK}

    public enum SEX {MEN, FEMALE}

    private String name;
    private String species;
    private COLOR color;
    private SEX sex;

    public Animal(String name, String species, COLOR color, SEX sex) {
        this.name = name;
        this.species = species;
        this.color = color;
        this.sex = sex;
    }

    // get & set
}
import java.util.ArrayList;
import java.util.List;

public class NoeShip {
    public static List

<animal> getAnimals() {
        List<animal> animals = new ArrayList&lt;&gt;();
        animals.add(new Animal("azor", "dog", Animal.COLOR.BROWN, Animal.SEX.MEN));
        animals.add(new Animal("mara", "cat", Animal.COLOR.GREY, Animal.SEX.FEMALE));
        animals.add(new Animal("michal", "human", Animal.COLOR.WHITE, Animal.SEX.MEN));
        animals.add(new Animal("cola", "bird", Animal.COLOR.BROWN, Animal.SEX.FEMALE));
        return animals;
    }
}

And now, we can log some information:

List<animal> animals = NoeShip.getAnimals();

        for (Animal animal : animals) {

            if (animal.getSex().equals(Animal.SEX.FEMALE)) {
                // log this ...
                System.out.println("Log: " + animal.getName());
            }

            if (animal.getColor().equals(Animal.COLOR.BROWN)) {
                // log this ...
                System.out.println("Log: " + animal.getName());
            }
        }

ass you can see this example is obvious, but not very clean. What we can do ?

Add interface, and prepare some more generic mechanizm

public interface AnimalFilter {
    public boolean check(Animal animal);
}

and now we can use our interface to create filters

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, new AnimalFilter() {
        @Override
        public boolean check(Animal animal) {
            return animal.getSex().equals(Animal.SEX.FEMALE);
        }
    });

    log(animal, new AnimalFilter() {
        @Override
        public boolean check(Animal animal) {
            return animal.getColor().equals(Animal.COLOR.BROWN);
        }
    });
}

better, but still ugly as f*

time for Lambda!

for (Animal animal : animals) {
    log(animal, (Animal a) -&gt; a.getSex().equals(Animal.SEX.FEMALE));
    log(animal, (Animal a) -&gt; a.getColor().equals(Animal.COLOR.BROWN));
}

better ? :)