Getting started with Java 8 – Part 2

Click here to read about Getting started with Java 8- Part 1

Functional Interface:-

You cannot use any interface with lambda expression. Only interfaces with one abstract method can be used with lambda expression. These type of interfaces are also called function interfaces.

Java 8 comes with many functional interfaces that you can use in your code.

Predicate ->

This functional interface is used to check if some condition is true or not. It has one abstract method named test that takes a value of type T and returns a

boolean. Let’s say we want to define a predicate that filters out all the even number from a list.

Predicate evenNumbers = name -> name % 2 == 0;
boolean test =  evenNumber.test(6);

Consumer ->

This functional interface represents an operation that accepts a single input argument and returns no result. It has a method called accept that take value of type T

and has void return type.

Consumer messageConsumer = message -> System.out.println(message);
messageConsumer.apply(“message”)

Function ->

This functional interface takes one argument as input and produces a result. Let’s say we want to find the length of a string.

Function<String, Integer> numberOfLetters = s -> s.length();
Integer length = numberOfLetters.apply(“word”);

Click here for Part 3

By:
Aditya Agrawal
www.coviam.com

2 thoughts on “Getting started with Java 8 – Part 2

Leave a Reply

Your email address will not be published.