四大类函数式接口

供给型接口

Supplier<T>     返回T类型对象
    T get();
Supplier<Apple> supplier = () -> new Apple();
// Supplier<Apple> supplier = Apple::new;
supplier.get();

消费型接口

Consumer<T>     接收一个 T 类型
    void accept(T t);
List<String> languages = Arrays.asList("java","scala","python");
Consumer<String> consumer = System.out::println;
languages.stream().forEach(consumer);

函数型接口

Function<T, R>  由T类型对象转成R类型对象
    R apply(T t);
List<String> languages = Arrays.asList("java","scala","python");
Function<String, Integer> ti = String::length;
languages.stream()
    .map(ti)
    .forEach(System.out::println);

断言型接口

Predicate<T>    条件判断
    boolean test(T t);
List<String> languages = Arrays.asList("java","scala","python");
Predicate<String> p = (str) -> str.length() > 4;
languages.stream()
    .filter(p)
    .forEach(System.out::println);

一个简单的使用多个函数式接口的例子:

List<String> languages = Arrays.asList("java","scala","python");
Function<String, Integer> ti = String::length;
BiConsumer<Integer, String> bi = (a, b) -> System.out.println(b + a);
IntPredicate ip = x -> x > 4;
IntPredicate ip1 = x -> x < 100;
IntUnaryOperator io = x -> x * x;
languages.stream()
    .map(ti)
    .map(io::applyAsInt)
    .filter(x->ip.and(ip1).test(x))
    .forEach(x -> bi.accept(x, "prefix_"));

部分函数式接口中有 default 方法, 可以进行组合使用!

猜你喜欢

转载自www.cnblogs.com/wansw/p/10225928.html
今日推荐