Lambda expressions were introduced from Java 8. This page is a memo page about how to use Java lambda expressions. Lambda expressions are easy to use when used in combination with the Stream API.
List<Integer> list = Arrays.asList(2, 9, 5, 7, 4);
for (Integer i : list) {
if (i >= 5) {
System.out.println(i);
}
}
List<Integer> list = Arrays.asList(2, 9, 5, 7, 4);
list.stream()
.filter(i -> i >= 5)
.forEach(System.out::println);
The lambda expression and Stream API can be used for clearer and more readable description. Below are examples of using lambda expressions and Stream API.
List<String> list = Arrays.asList("b", "c", "a", "c", "b");
list.stream()
.sorted()
.forEach(System.out::println);
List<String> list = Arrays.asList("b", "c", "a", "c", "b");
list.stream()
.sorted((s1, s2) -> s2.compareTo(s1))
.forEach(System.out::println);
List<String> list = Arrays.asList("b", "c", "a", "c", "b");
list.stream()
.distinct()
.forEach(System.out::println);
List<Integer> list = Arrays.asList(2, 9, 5, 7, 4);
long count = list.stream()
.filter(i -> i >= 5)
.count();
System.out.println(count);
List<Integer> list = Arrays.asList(2, 9, 5, 7, 4);
int sum = list.stream()
.filter(i -> i >= 5)
.mapToInt(i -> i)
.sum();
System.out.println(sum);
IntStream.range(0, 10)
.parallel()
.forEach(System.out::println);
Recommended Posts