[Java] Where to Use Java Lambda Expressions

1 minute read

Overview

Lambda expression was introduced from Java8. This page is a memo page on the usage of Java lambda expressions. Lambda expressions are easy to use when used in combination with Stream API.

Extract values from list under certain conditions

Lambda expression, no use of Stream API

List<Integer> list = Arrays.asList(2, 9, 5, 7, 4);

for (Integer i: list) {
    if (i >= 5) {
        System.out.println(i);
    }
}

Lambda expression, using Stream API

List<Integer> list = Arrays.asList(2, 9, 5, 7, 4);

list.stream()
        .filter(i -> i >= 5)
        .forEach(System.out::println);

It is easier to read with better readability by using Lambda expression and Stream API. The following are examples of using lambda expression and Stream API.

Dictionary order

List<String> list = Arrays.asList("b", "c", "a", "c", "b");

list.stream()
        .sorted()
        .forEach(System.out::println);

Reverse dictionary sort

List<String> list = Arrays.asList("b", "c", "a", "c", "b");

list.stream()
        .sorted((s1, s2) -> s2.compareTo(s1))
        .forEach(System.out::println);

Duplicate deletion

List<String> list = Arrays.asList("b", "c", "a", "c", "b");

list.stream()
        .distinct()
        .forEach(System.out::println);

Count the number of values ##5 or more

List<Integer> list = Arrays.asList(2, 9, 5, 7, 4);

long count = list.stream()
        .filter(i -> i >= 5)
        .count();

System.out.println(count);

Add values ##5 and above

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);

Output the value of ##1~10 by multi-thread

IntStream.range(0, 10)
        .parallel()
        .forEach(System.out::println);