Java 8 - Functional Interfaces


These interfaces are likewise called Single Abstract Method interfaces (SAM Interfaces). These can be spoken to utilizing Lambda articulations, Method reference and constructor references also. Java 8 presents an annotation

Let's assemble our first practical interface:

package functionalInterfaceExample;
 
@FunctionalInterface
public interface MyFirstFunctionalInterface {
public void firstWork();
}

Java8Tester.java

import java.util.Arrays; 

import java.util.List; 

import java.util.function.Predicate; 

public class Java8Tester { 

public static void main(String args[]) { 

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9); 

//Predicate<Integer> predicate = n - > true 

//n is finished as parameter to test technique for Predicate interface 

//test strategy will dependably return genuine regardless of what esteem n has. 

System.out.println("Print all numbers:"); 

//pass n as parameter 

eval(list, n->true); 

//Predicate<Integer> predicate1 = n - > n%2 == 0 

//n is finished as parameter to test strategy for Predicate interface 

//test technique will return genuine if n%2 comes to be zero 

System.out.println("Print even numbers:"); 

eval(list, n-> n%2 == 0 ); 

//Predicate<Integer> predicate2 = n - > n > 3 

//n is breezed through as parameter to test strategy for Predicate interface 

//test strategy will return genuine if n is more noteworthy than 3. 

System.out.println("Print numbers more noteworthy than 3:"); 

eval(list, n-> n > 3 ); 

} 

public static void eval(List<Integer> list, Predicate<Integer> predicate) { 

for(Integer n: list) { 

if(predicate.test(n)) { 

System.out.println(n + " "); 

} 

} 

} 

}
Run precedent »

Here we've passed Predicate interface, which takes a solitary information and returns Boolean.

Verify the Result

Compile the class utilizing javac compiler as pursues −

C:\JAVA>javac Java8Tester.java 

 Print all numbers: 

1 

2 

3 

4 

5 

6 

7 

8 

9 

Print even numbers: 

2 

4 

6 

8 

Print numbers more noteworthy than 3: 

4 

5 

6 

7 

8 

9 






javacodegeeks is optimized for learning.© javacodegeeks .
All Right Reserved and you agree to have read and accepted our term and condition