Functional interfaces : Key programming feature java 8

Functional interfaces contain only one abstract method. It is used as a parameter when lyamda expression or method reference is passed as an argument.
 
 Java 8 defined functional interfaces :
    1. Predicate
It performs a test that returns true or false. Eg,
public interface Predicate<T> {
boolean test(T t);
}

List<Integer> list = new ArrayList<>(Arrays.asList(1, 3,4 ));
System.out.printlin(list);

list.removeIf(i -> i % 2 === 0);
//predicate lyamda that removes even element in the list
//i is shorthand for element leverages by java compiler's type inference capabilities
//this predicate lyamda mathces a signagure of test method in interface which takes one parameter and return boolean

System.out.printlin(list);

2. Function or Func
It applies a computation on 1 parameter and returns a result. Eg.
public interface Function<T, R> {
R apply(T t);
}

List<Thread> threads = new ArrayList<>(Arrays.asList(new Thread("Thread 1"), new Thread("Thread 2")));
System.out.printlin(threads);

threads.sort(Comparator.comparing(Thread::getName));
System.out.printlin(threads);

3. BiFunction
This applies a computation on 2 parameters and returns a result. Eg.
public interface BiFunction<T, U, R> {
R apply(T t, U u);
}

Map<String, Integer> iqMap = new HashMap<String, Integer>() {
put("san", 100), put("bhu", 100);
};

iqMap.replaceAll((k, v) -> v - 50);

Java 7 or below doing way :
for(Map.Entry<String, Integer> entry : iqMap.entrySet()){
entry.setValue(entry.getValue() - 50);
}

4. Consumer
This accepts a parameter and returns no results. Basically, it consumes the data. Eg.
public interface Consumer<T>{
void accept(T t);
}


List<Thread> threads = new ArrayList<>(Arrays.asList(new Thread("Thread 1"), new Thread("Thread 2")));
threads.forEach(System.out::printlin);
//For each of the element, as a side effect the printlin the consumer print out the element

5. Supplier
This returns a value and takes no parameter. Eg.
public interface Supplier<T> {
T get();
}

Supplier<Employee> supplier = Employee::new;
//Supplier has given a constructor reference for Employee class

System.out.printlin(supplier.get().getName());
//supplier get supplies a instance of employee class


Reference : https://www.youtube.com/watch?v=ypPGG6vmMM4&t=2416s

Comments