Java 8 新特性

Lambda、函数式接口、Stream、Optional 与新的日期 API。

Intermediate
Key PointsLambda 让函数成为值;Stream 用声明式管道处理集合;Optional 显式表达「可能没有值」。

Lambda 表达式

(params) -> expr is shorthand for an anonymous function, usable only with functional interfaces (one abstract method). It makes passing behaviour as easy as passing a value.

Java
import java.util.ArrayList;
import java.util.List;

public class LambdaDemo {
    public static void main(String[] args) {
        Runnable r = () -> System.out.println("run");
        r.run();

        List<String> list = new ArrayList<>(List.of("b", "a"));
        list.sort((x, y) -> x.compareTo(y));
        System.out.println(list);

        list.forEach(s -> System.out.print(s + " "));
        System.out.println();
    }
}
Output
run
[a, b]
a b 

函数式接口与方法引用

Function<T,R>, Consumer<T>, Supplier<T> and Predicate<T> are the standard functional interfaces. A method reference Type::method is a further shorthand.

Java
import java.util.function.Function;
import java.util.function.Predicate;

public class FunctionalDemo {
    public static void main(String[] args) {
        Function<String, Integer> len = String::length;
        Predicate<String> empty = String::isEmpty;

        System.out.println(len.apply("hello"));
        System.out.println(empty.test(""));
        System.out.println(len.andThen(n -> n * 2).apply("abc"));
    }
}
Output
5
true
6

Stream 流

A Stream is a pipeline: filter, map, sorted, collect, reduce. It is lazy — nothing runs until a terminal operation is invoked.

Java
import java.util.List;
import java.util.stream.Collectors;

public class StreamDemo {
    public static void main(String[] args) {
        List<Integer> nums = List.of(1, 2, 3, 4, 5, 6);

        List<Integer> evens = nums.stream()
                .filter(n -> n % 2 == 0)
                .map(n -> n * 10)
                .collect(Collectors.toList());

        System.out.println(evens);
        System.out.println(nums.stream().mapToInt(Integer::intValue).sum());
        System.out.println(nums.stream().anyMatch(n -> n > 5));
        System.out.println(nums.stream().count());
    }
}
Output
[20, 40, 60]
21
true
6

Optional

Optional makes "maybe absent" explicit and forces the caller to handle it: orElse for defaults, map to transform, ifPresent to run conditionally. Do not use it for fields or parameters.

Java
import java.util.Optional;

public class OptionalDemo {
    public static void main(String[] args) {
        Optional<String> a = Optional.of("x");
        Optional<String> b = Optional.empty();

        System.out.println(a.isPresent());
        System.out.println(b.isPresent());
        System.out.println(b.orElse("default"));
        System.out.println(a.map(String::length).orElse(0));
    }
}
Output
true
false
default
1

Friends & Partners