Lambda Expression In Java
A function has 4 things:- Name Return type Parameter list. –needed to given by developer Body –needed to be given by developer in lambda expression
A lambda expression has parameter list and body
Example:
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
public class Sample {
public static void main(String[] args) {
List<Integer> numbers= Arrays.asList(1,2,3,4,5,6,7,8,9,10);
//Internal Iterators
numbers.forEach(new Consumer<Integer>() {
@Override
public void accept(final Integer integer) {
System.out.println(integer);
}
});
System.out.println("------");
//In lambda expression we remove the ceremony code
numbers.forEach((Integer value)-> System.out.println(value));
System.out.println("------");
// We can reduce the noise further
numbers.forEach(value->System.out.println(value));
}
}
- Java 8 has Type Inference but ONLY for Lambda Expression