1A lambda expression is a short block
2of code which takes in parameters
3and returns a value. Lambda expressions
4are similar to methods, but they do
5not need a name and they can be
6implemented right in the body of a method.
7
8parameter -> expression
9
10To use more than one parameter, wrap them in parentheses:
11
12(parameter1, parameter2) -> expression
13
14Example
15Use a lamba expression in the ArrayList's
16forEach() method to print every item in the list:
17
18import java.util.ArrayList;
19
20public class Main {
21 public static void main(String[] args) {
22 ArrayList<Integer> numbers = new ArrayList<Integer>();
23 numbers.add(5);
24 numbers.add(9);
25 numbers.add(8);
26 numbers.add(1);
27 numbers.forEach( (n) -> { System.out.println(n); } );
28 }
29}
30
1A lambda expression is a short block
2of code which takes in parameters
3and returns a value. Lambda expressions
4are similar to methods, but they do
5not need a name and they can be
6implemented right in the body of a method.
7
8parameter -> expression
9
10To use more than one parameter, wrap them in parentheses:
11
12(parameter1, parameter2) -> expression
13
14Example
15Use a lamba expression in the ArrayList's
16forEach() method to print every item in the list:
17
18import java.util.ArrayList;
19
20public class Main {
21 public static void main(String[] args) {
22 ArrayList<Integer> numbers = new ArrayList<Integer>();
23 numbers.add(5);
24 numbers.add(9);
25 numbers.add(8);
26 numbers.add(1);
27 numbers.forEach( (n) -> { System.out.println(n); } );
28 }
29}
1Comparator<Developer> byName =
2 (Developer o1, Developer o2)->o1.getName().compareTo(o2.getName());
1StateOwner stateOwner = new StateOwner();
2
3stateOwner.addStateListener(
4 (oldState, newState) -> System.out.println("State changed")
5);
6
1public class TestLambda {
2
3 public static void main(String args[]) {
4 List<String> lowerCaseStringsList = Arrays.asList("a","b","c");
5 // the :: notation is the lambda expression
6 // it's the same as the anonymous function s -> s.toUpperCase()
7 List<String> upperCaseStringsList = lowerCaseStringsList.stream().
8 map(String::toUpperCase).
9 collect(Collectors.toList());
10 }
11}