Java 8 - Lambda Expressions


We'll do something interesting today.Let's make a simple student management application which you can insert students,get the information of the students and filter them according to the given conditions.First let's create the basic Person class which is going to help us in entering,getting and filtering student details.
public class Person {
   public enum Sex {
        MALE, FEMALE
    }
    String name;
    Sex gender;
    String emailAddress;
    int age;

    Person(){}
    Person(String name, String emailAddress, int age, Sex gender) {
        this.name = name;
        this.emailAddress = emailAddress;
        this.age = age;
        this.gender = gender;
    }
    public String getName() {
        return name;
    }
    public int getAge() {
        return age;
    }
    public String getEmail() {
        return emailAddress;
    }
    public Sex getSex() {
        return gender;
    }
    public void printPerson() {
        System.out.println(name + "," + gender + "," + emailAddress + "," + age);
    }
}
Simple and straightforward.You can insert a person by creating an object of Person class and get the information of a specific person using the relevant object of that person.Assume we want to filter people according to their gender and age.We'll do this in two ways. One way is creating a simple method.We'll name this method as filterPerson.
void filterPerson(List<Person> people, int low, int high) {
        for (Person person : people) {
            if (person.getAge() > low && person.getAge() < high && person.getSex() ==                  person.gender.MALE) {
                person.printPerson();
           }
       }
 }
Alright let's create our small people database .
List<Person> peeps=new ArrayList<>();
peeps.add(new Person("Hasitha","hasitha@gmail.com",23,Sex.MALE));
peeps.add(new Person("Nadishan","nadishan@gmail.com",25,Sex.MALE));
peeps.add(new Person("Jayasundara","jayasundara@gmail.com",18,Sex.MALE));
Now we can check the validity of our method.
 Person com=new Person();
 com.filterPerson(peeps,20 ,24);
The output is Hasitha,MALE,hasitha@gmail.com,23 which means we are on the right track.Let's do this in another way using an interface,
public interface TestPerson {
      public boolean test(Person person, int low, int high);
}

We are going to test the person using an interface.We'll implement this interface in another class,override the method and add the logic we need.

public class InterfaceTest implements TestPerson {
    @Override
    public boolean test(Person person, int low, int high) {
        return person.gender == person.gender.MALE && person.getAge() > low && person.getAge() < high;
    }
}

Each and everything is pretty straightforward up to now.Now all we have to do is create a new method.
void filterPerson(List<Person> people, TestPerson test, int low, int high) {
        for (Person person : people) {
            if (test.test(person, low, high)) {
                person.printPerson();}}}
Now check the validity of method.
com.filterPerson(peeps,new InterfaceTest(),20, 24);
The output is Hasitha,MALE,hasitha@gmail.com,23.Wow we are doing great.Now look at the following example.

com.filterPerson(peeps,new TestPerson() {
            @Override
            public boolean test(Person person, int low, int high) {
                return person.gender == person.gender.MALE && person.getAge() > low && person.getAge() < high;
            }
        }, 20, 24);
The output is Hasitha,MALE,hasitha@gmail.com,23.Same result but another way of implementing the solution.This is where Lambda expressions comes in handy.We can simplify the above implementation as follows.
com.filterPerson(peeps,(person,low,high)->{
return person.gender == person.gender.MALE && person.getAge() > low && person.getAge() < high;
}, 20, 24);
Less code and damn...!!!!It's so beautiful.We'll now stream the given arraylist and perform the above steps in more convenient and beautiful way.
peeps.stream().filter(person->person.age>20 && person.age<24 && person.gender==person.gender.MALE).forEach(filterdPerson->filterdPerson.printPerson());
We reduced several lines of code to one line with the use of lambda expressions.
Runnable r=()->{
     System.out.println("I am new thread");
};
ExecutorService executorService = Executors.newFixedThreadPool(1);
executorService.execute(r);
executorService.shutdown();
The output is "I'm a new thread".See the beauty of lambda expressions.Below you get the old implementation of threads.Using lambda expressions we are able to reduce a considerable number of  code lines while adding elegance and neatness to the code.
Runnable r=new Runnable() {
            @Override
            public void run() {
                System.out.println("I am new thread");
           }
};

Comments