Professional Documents
Culture Documents
It means, taking a block of code and making it available without executing. This
block of code can be called later by other parts of your programs.
You can pass the block of code as an argument to other method that will
execute later.
Passing Code with Behavior Parameterization
AppleGreenColorPredicate AppleHeavyWeightPredicate
Anonymous classes are like the local classes (class defined in a block).
They allow you to declare and instantiate a class at the same time
List<Apple> redApples = filterApples(inventory, new ApplePredicate() {
@Override
public boolean test(Apple apple) {
return apple.getColor().equals(Color.RED);
}
});
System.out.println(redApples);
It does not have a name, but it has a list of parameters, a body, and a return
type, and also possibly a list of exceptions that can be thrown.
Arrow
(Apple a) -> a.getWeight() > 150 Takes one parameter of type Apple and returns a boolean.
@FunctionalInterface
public interface ApplePredicate {
boolean test(Apple apple);
}
Which of these interfaces are functional interfaces?
}
Java API-Functional Interfaces
- Predicate
- Consumer
- Function
- Supplier
- Runnable
Predicate
You can use this interface when you need to represent a boolean expression
that uses an object of type T.
@FunctionalInterface
public interface Predicate<T> {
boolean test(T t);
}
Predicate<Integer> lesserThan = new Predicate<Integer>() {
@Override
public boolean test(Integer integer) {
return integer<18;
} Without Lambda
};
System.out.println(lesserThan.test(10)); //true
You can use this interface when you need to access an object of type T and
perform some operations on it. For example : forEach
@FunctionalInterface
public interface Consumer<T> {
void accept(T t);
}
Consumer<Integer> display = new Consumer<Integer>() {
@Override
public void accept(Integer integer) {
System.out.println(integer);
Without Lambda
}
};
display.accept(10);
You can use this interface when you need to define a lambda that maps
information from an input object to an output.
@FunctionalInterface
public interface Function<T,R> {
R apply(T t);
}
Function<Integer, Double> convert =
new Function<Integer, Double>() {
@Override
public Double apply(Integer integer) {
Without Lambda
return integer.doubleValue();
}
};
System.out.println(convert.apply(10)); //10.0
Supplier<T> interface defines an abstract method named get that does not take
any argument but produces a value of type T
@FunctionalInterface
public interface Supplier<T> {
T get();
}
Supplier<Double> randomValue = new Supplier<Double>() {
@Override
public Double get() {
return Math.random();
Without Lambda
}
};
System.out.println(randomValue.get());