Java系列4---认识Java8

122 阅读1分钟
行为参数化
lambda可以用在哪些地方?
    函数式接口(只定义一个抽象方法的接口)
常见的函数式接口有哪些?
    Comparator
        apples.sort(new Comparator<Apple>() {
            @Override
            public int compare(Apple o1, Apple o2) {
                return o1.getWeight().compareTo(o2.getWeight());
            }
        });
        apples.sort((Apple a1,Apple a2) -> a1.getWeight().compareTo(a2.getWeight()));
    Runnable
        Thread tt = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello world");
            }
        });
        Thread t = new Thread(() -> System.out.println("hello world"));
    Callable
    java.util.function包下
方法引用:lambda表达式的快捷写法
    apples.sort((Apple a1,Apple a2) -> a1.getWeight().compareTo(a2.getWeight()));
    以下是对一个list按照重量排序的最优方案
    apples.sort(Comparator.comparing(Apple::getWeight));//方法引用
Stream(对比集合)
    集合讲的是数据,流讲的是计算
    短路、循环合并
    源、中间操作、终端操作
    使用流:
        筛选和切片
            filter
            distinct
            limit
            skip
        映射
            map
            flatMap
        查找和匹配
            anyMatch
            allMatch
            noneMatch
            findAny
            findFirst
        归约
            reduce
            count
        sorted
        forEach
        collect
收集器
    Collector
    Collectors
流水线、并行
    注意: 
        原始类型的装箱和拆箱操作会影响性能
        避免共享可变状态
    数据结构的选取
    是否使用并行
利用Java8重构:
    匿名类---》lambda
    lambda---》方法引用
    命令式的数据处理---》stream
    设计模式:
        策略模式
        模板方法
        观察者模式
        责任链模式
        工厂模式
    peek方法调试日志
默认方法:类库的设计者要更新接口,添加新的方法,实现不用变动的一种解决办法,另一种是在接口中声明静态方法
    默认方法的引入就是为了以兼容的方式解决类库的演进过程的。
Optional:取代null
CompletableFuture(组合式异步编程)
java.time.*(新的日期和时间API)

以上便是Java8的一些新特性,可能不全,以后有用到再补充。
Java7
    带资源的try语句
    菱形运算符
    分支/合并框架
Java5
    for-each
    Future接口