内置四大函数接口
- 消费型接口: Consumer< T> void accept(T t)有参数,无返回值的抽象方法;
比如: map.forEach(BiConsumer<A, T>)
Consumer<Person> greeter = (p) -> System.out.println("Hello, " + p.firstName); greeter.accept(new Person("Luke", "Skywalker"));
- 供给型接口: Supplier < T> T get() 无参有返回值的抽象方法;
Supplier<Person> personSupplier = Person::new; personSupplier.get(); // new Person
- 断定型接口: Predicate<T> boolean test(T t):有参,但是返回值类型是固定的boolean
Predicate<String> predicate = (s) -> s.length() > 0; predicate.test("foo"); // true predicate.negate().test("foo"); // false Predicate<Boolean> nonNull = Objects::nonNull; Predicate<Boolean> isNull = Objects::isNull; Predicate<String> isEmpty = String::isEmpty; Predicate<String> isNotEmpty = isEmpty.negate();
比如: steam().filter()中参数就是Predicate
- 函数型接口: Function<T,R> R apply(T t)有参有返回值的抽象方法;
Function<String, Integer> toInteger = Integer::valueOf; Function<String, String> backToString = toInteger.andThen(String::valueOf); backToString.apply("123"); // "123"