×

常用Java8语法小结

我的笔记 我的笔记 发表于2019-02-14 14:58:00 浏览2485 评论0

抢沙发发表评论

package com.ihome.prepay.hotel;

import java.time.*;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.*;
import java.util.stream.Collectors;

/**
 * Java8Test
 *
 *@author yanguoqing
 *@date 2019/2/13
*/
public class Java8Test {

    class Stu {
        Integer id;
        String name;
        Integer sex;
        Boolean flag;

        public Stu() {
        }

        public Stu(Integer id, String name, Integer sex, Boolean flag) {
            this.id = id;
            this.name = name;
            this.sex = sex;
            this.flag = flag;
        }

        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Integer getSex() {
            return sex;
        }

        public void setSex(Integer sex) {
            this.sex = sex;
        }

        public Boolean getFlag() {
            return flag;
        }

        public void setFlag(Boolean flag) {
            this.flag = flag;
        }
    }

    // 1. Lambda 表达式  java.util.function.*
    {
        // 提供者
        Supplier<Integer> supplier = () -> 5;
        // 消费者
        Consumer<Integer> consumer = (Integer a) -> System.out.println(a);
        // 消费者(缩写)
        Consumer<Integer> consumer2 = a -> System.out.println(a);
        // 二元消费者
        BiConsumer<Integer, Integer> biConsumer = (a, b) -> System.out.println(a + b);
        // 函数 接收一个参数,返回一个结果
        Function<Integer, Integer> function = a -> a + 1;
        // 二元函数 接收两个参数,返回一个结果
        BiFunction<Integer, Integer, Integer> biFunction = (a, b) -> a + b;
        // 二元操作 接收两个同类型的参数,返回一个同类型结果 继承BiFunction
        BinaryOperator<Integer> binaryOperator = (a, b) -> a + b;
        // 接收一个参数,返回一个boolean类型的结果
        Predicate<Integer> predicate = a -> a > 5;

        // 如果一个接口只有一个方法 就可以使用Lambda表达式代表这个接口的一个实例 如 Runnable Comparator
        new Thread(() -> {});
    }

    // 2. 函数引用
    {
        // 方法引用
        List<String> list = Arrays.asList("1", "2", "3");
        list.forEach(System.out::println);
        // 构造器引用
        Supplier<Stu> supplier = Stu::new;
    }

    // 3. Stream 流式接口
    {
        Stu stu1 = new Stu(1, "stu1", 1, Boolean.TRUE);
        Stu stu2 = new Stu(3, "stu2", 2, Boolean.FALSE);
        Stu stu3 = new Stu(2, "stu3", 1, Boolean.TRUE);
        Stu stu4 = new Stu(4, "stu4", 2, Boolean.FALSE);
        List<Stu> stus = Arrays.asList(stu1, stu2, stu3, stu4);

        // id正序 等价于stus.sort((o1, o2) -> o1.getId().compareTo(o2.getId()));
        stus.sort(Comparator.comparing(Stu::getId));
        // id倒序
        stus.sort((o1, o2) -> o2.getId().compareTo(o1.getId()));
        // 特殊排序 flag为ture排在前面
        stus.sort((o1, o2) -> o2.getFlag() ? 1 : -1);

        // 提取id 获得id集合
        stus.stream().map(Stu::getId).collect(Collectors.toList());
        // 过滤 获得flag为ture的Stu
        stus.stream().filter(Stu::getFlag).collect(Collectors.toList());
        // 过滤 获得flag为false的Stu
        stus.stream().filter(o -> !o.getFlag()).collect(Collectors.toList());

        // list转map key为id value为Stu
        // Function.identity() 等效 a -> a 返回对象本身
        Map<Integer, Stu> stuMap = stus.stream().collect(Collectors.toMap(Stu::getId, Function.identity()));

        // 根据性别分组
        Map<Integer, List<Stu>> stuMap2 = stus.stream().collect(Collectors.groupingBy(Stu::getSex));

        // 合并姓名 以逗号分割
        stus.stream().map(Stu::getName).collect(Collectors.joining(","));

        // 取id最大值
        OptionalInt max = stus.stream().mapToInt(Stu::getId).max();
        // Optional 参见https://www.cnblogs.com/KingKirito1024/p/10346690.html
        // max.isPresent() ? max.getAsInt() : 0;
        max.orElse(0);

    }

    // CompletableFuture 多线程
    {
        List<Integer> list = Arrays.asList(1, 2, 3, 4);
        // 异步执行 使用的是默认的ForkJoinPool
        list.forEach(o -> CompletableFuture.runAsync(() -> System.out.println(Thread.currentThread().getName() + "------" + o * 2)));
        ExecutorService executorService = Executors.newFixedThreadPool(4);
        // 使用自己定义的线程池
        list.forEach(o -> CompletableFuture.runAsync(() -> System.out.println(Thread.currentThread().getName() + "------" + o * 2), executorService));

        List<Integer> result = new ArrayList<>();
        CompletableFuture[] completableFutures = list.stream().map(o -> CompletableFuture.supplyAsync(() -> o + 1)
//                .thenApply(t -> t + 2) // 可以不要
                .whenComplete((r, e) -> {
                    if (e != null) {
                        System.out.println(e.getMessage());
                    }else {
                        result.add(r);
                    }
                })
        ).toArray(CompletableFuture[]::new);
        // join会阻塞主线程,等待所以任务线程执行完成
        CompletableFuture.allOf(completableFutures).join();
        result.forEach(System.out::println);
    }

    // 时间类
    {
        // Instant
        Instant.now(); // 获取当前时间戳
        // LocalDate
        LocalDate.now(); // 2019-02-13
        // LocalTime
        LocalTime.now(); // 18:19:15
        // LocalDateTime
        LocalDateTime.now(); // 2019-02-13 18:19:15
    }
}

 

我的笔记博客版权我的笔记博客版权