Wednesday, March 23, 2022

Built-in Functional Interfaces

 

Functional Interface

An interface that contains only a single abstract (unimplemented) method. It can have contain default and static methods which do have an implementation in addition to the abstract method.

Built-in Functional Interfaces

A set of functional interfaces designed for commonly occuring use cases is already built in java.

  1. Function Interface: represents an abstract method, apply(), that takes a single parameter and returns a single value.

    //implementing function interface
    public class GetSquare implements Function<Integer, Integer> {
     @Override
     public Long apply(Integer number) {
         return number * number;
     }
    }
    //using the above implementation
    Function<Integer, Integer> getSquare = new GetSquare();
    Integer result = getSquare.apply(4);
    System.out.println("result = " + result);
    
    //inline implementation using lambda expression
    Function<Integer, Integer> getSquare = number -> number * number;
    Integer result = getSquare.apply(4);
    System.out.println("result = " + result);
    
  2. Predicate: represents an abstract method, test(), that takes a single value as parameter, and returns true or false.
    //checks whether a value is greater than 100
    Predicate<Integer> greaterThan = v -> (v > 100);
    System.out.println(greaterThan.test(1050));
    
  3. Supplier: represents an abstract method, get(), that supplies a value.
    //function returns a random value.
    Supplier<Double> randomValue = () -> Math.random();
    System.out.println(randomValue.get());
    
  4. Consumer: represents an abstract method, accept(), that consumes a value without returning any value. Used for printing or writing to a file etc.

    //consumer to display a number
    Consumer<Integer> consumer = value -> System.out.println(value);
    consumer.accept(10)
    
    //consumer to display a list of numbers
    Consumer<List<Integer>> displayList = list -> list.stream().forEach(v -> System.out.print(v + " "));
    List<Integer> list = new ArrayList<Integer>();
    list.add(2);
    list.add(1);
    list.add(3);
    displayList.accept(list);

No comments:

Post a Comment