5 mins might be useful if you spend on this page. This is a quick hands on one of the cool feature of java 8. It is helps to reduce the lot of boiler plate code and focused many runtime implementation using @FunctionalInterface.
@FunctionalInterface -> A interface which has only one abstract method. It can contain any number of default and static method.
We will be talking about Predicate (shown below).
@FunctionalInterface interface Predicate<T> Predicate has one abstract method -> boolean test(T t)
We can write any runtime implementation using Lambda and get the result. Lets see the Predicate example in java 8.
Let the game begin:
I have created User Class. Used Lombok plugin for getter and setter method, Builder for creating object. You can use normal IDE generated getter, setters, constructors.
import lombok.Builder;
import lombok.Data;
@Data
@Builder
public class User {
private String name;
private String place;
private int age;
private String education;
private String color;
}
Creating a List of users:
List<User> users=new ArrayList<>();
users.add(User.builder().name("Rockey").place("London").age(32).color("Brown").education("B.Tech").build());
users.add(User.builder().name("Rohit").place("India").age(23).color("Fair").education("B.Tech").build());
users.add(User.builder().name("Ana").place("London").age(32).color("Fair").education("Event").build());
users.add(User.builder().name("Lucy").place("UK").age(18).color("Fair").education("B.Tech").build());
users.add(User.builder().name("Steve").place("USA").age(32).color("Brown").education("B.Tech").build());
users.add(User.builder().name("Robin").place("India").age(19).color("Fair").education("Diploma").build());
users.add(User.builder().name("Kumar").place("India").age(35).color("Brown").education("B.Tech").build());
users.add(User.builder().name("Gupta").place("USA").age(45).color("Brown").education("Teacher").build());
users.add(User.builder().name("Joe").place("UK").age(48).color("Brown").education("B.Tech").build());
Unleash the devil
Create a Predicate for users who has age more than 30 years.
Predicate<User> listOfUserMoethan30= t -> t.getAge() > 30;
Use the predicate to filter data from the stream:
users.stream().filter(listOfUserMoethan30).forEach(System.out :: println);
We can merge above two codes to below one :
users.stream().filter(t -> t.getAge() > 30).forEach(System.out :: println);
Output:
User(name=Rockey, place=London, age=32, education=B.Tech, color=Brown)
User(name=Ana, place=London, age=32, education=Event, color=Fair)
User(name=Steve, place=USA, age=32, education=B.Tech, color=Brown)
User(name=Kumar, place=India, age=35, education=B.Tech, color=Brown)
User(name=Gupta, place=USA, age=45, education=Teacher, color=Brown)
User(name=Joe, place=UK, age=48, education=B.Tech, color=Brown)
This is for understanding how test(T t) works.
Thanks for reading!!!