java1.8 新特性

一、函数接口

@FunctionalInterface // 函数接口
interface Demo {
    // 可以重写Object的方法
    String toString();
    // 只能有一个抽象方法
    void a();
    // 可以有 default 方法
    default void b() {}
    // 可以有 static 方法
    static void c() {}
}
View Code

二、jdk自带的一些函数接口

Supplier<T> T get();  
Predicate<T> boolean test(T t);  
Consumer<T> void accept(T t);  
Function<T, R> R apply(T t);  
UnaryOperator<T> extends Function<T, T> R apply(T t); 继承、泛型,所以接口函数实际上是:T apply(T t1, T t2);
BiConsumer<T, U> void accept(T t, U u);  
BiFunction<T, U, R> R apply(T t, U u);  
BinaryOperator<T> extends BiFunction<T,T,T> R apply(T t, U u); 继承、泛型,所以接口函数实际上是:T apply(T t1, T t2);
ToIntFunction<T> int applyAsInt(T value);  
ToIntBiFunction<T, U> int applyAsInt(T t, U u);  
IntFunction<R> R apply(int value);  
ToIntBiFunction<T, U> int applyAsInt(T t, U u);  

三、lambda表达式

1、多线程,lambda表达式实现Runbale接口

    public static void main(String[] args) {
        for (int i = 0; i < 20; i++) {
            new Thread(() -> System.out.println(Thread.currentThread().getName())).start();
        }
    }
View Code

2、jdk1.8中添加了一个 ThreadLocal 的 Lambda 构造方式

public class Demo {
    ThreadLocal<String> threadLocal = ThreadLocal.withInitial(() -> "");
}

3、forEach方法,jdk1.8迭代器接口里新增了一个defaut方法——forEach方法,用lambda表达式实现forEach方法的参数——Consumer函数接口

        String[] strArr = {"中", "华", "民", "国"};
        List<String> strList = Arrays.asList(strArr);
        strList.forEach((item) -> System.out.println(item));
View Code
        HashMap<Object, Object> map = new HashMap<>();
        map.put("中国", "北京");
        map.put("美国", "纽约");
        map.put("英国", "伦敦");
        map.forEach((k, v) -> System.out.println(k  + "-" + v));
View Code

4、List的sort方法,用lambda表达式实现sort方法的参数——Comparator函数接口

    public static void main(String[] args) {
        String[] strArr = {"中", "华", "民", "国"};
        List<String> strList = Arrays.asList(strArr);
        System.out.println(strList);
        strList.sort((o1, o2) -> o1.compareTo(o2));
        System.out.println(strList);
    }
View Code

 

posted @ 2020-03-18 16:20  zhuangrunwei  阅读(139)  评论(0编辑  收藏  举报