Lamdas
Lambdas are a way of using functional programming to develop concise and powerful Java code since Java version 8.
Lambdas implement functional interfaces using the @FunctionalInterface annotation which will contain a single method that allows you to pass functions as data dynamically.
Previously, functions had to be contained in a class.
java.util.function contains a number of useful functional interfaces for writing lambdas by passing in arguments and either outputting something or returning nothing.
Functional interfaces
Consumer
A consumer is a functional interface that accepts an input and does not produce an output.
ArrayList<String> students = new ArrayList<>();
students.add("Naiomi");
students.add("Teyte");
students.add("Myloh");
Consumer<String> printItem = n -> System.out.println(n);
students.forEach(printItem);
Function
A function takes an input and produces an output. An example of this is the stream.map() method.
Function<Integer, Integer> doubly = n -> n + n;
System.out.println(doubly.apply(8));
Supplier
A supplier does not take any inputs but produces an output. It has only one method get() and does not have any default and static methods.
Supplier<Double> randomNumUnder100 = Math.random() * 100;
System.out.println(randomNumUnder100.get());
Supplier<Double> randomNumUnder100 = Math.random() * 100;
System.out.println(randomNumUnder100.get());
Predicate
The predicate interface accepts an argument and returns a boolean value. The filter method of a stream accepts a predicate to filter the data.
IntPredicate isDivByTwo = n -> n / 2 == 0;
System.out.println(isDiveMyTwo(9));
Scenario: Calculate the value of 2 numbers multiplied by each other and then added to a random number
Implement a functional interface
@FunctionalInterface
public interface Calculator {
int calculate(int x, int y);
}
Implement the calculate method
public static void main(String[] args) {
Calculator calculator = (x, y) -> {
Random random = new Random();
int randomNumber = random.nextInt(50);
return x * y + randomNumber;
};
System.out.println(calculator.calculate(1, 2));
}