java8语法总结

菜鸟地址:https://www.runoob.com/java/java8-new-features.html

Java8 新增了非常多的特性:

  • Lambda 表达式 − Lambda允许把函数作为一个方法的参数(函数作为参数传递进方法中。

  • 方法引用 − 方法引用提供了非常有用的语法,可以直接引用已有Java类或对象(实例)的方法或构造器。与lambda联合使用,方法引用可以使语言的构造更紧凑简洁,减少冗余代码。

  • 默认方法 − 默认方法就是一个在接口里面有了一个实现的方法。

  • 新工具 − 新的编译工具,如:Nashorn引擎 jjs、 类依赖分析器jdeps。

  • Stream API −新添加的Stream API(java.util.stream) 把真正的函数式编程风格引入到Java中。

  • Date Time API − 加强对日期与时间的处理。

  • Optional 类 − Optional 类已经成为 Java 8 类库的一部分,用来解决空指针异常。

  • Nashorn, JavaScript 引擎 − Java 8提供了一个新的Nashorn javascript引擎,它允许我们在JVM上运行特定的javascript应用。

// 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
    }

项目中常常遇到的问题:

1、日期问题。项目中有时会遇到spring时区转换问题。

// 获取当前的日期时间
      LocalDateTime currentTime = LocalDateTime.now();
      System.out.println("当前时间: " + currentTime);
        
      LocalDate date1 = currentTime.toLocalDate();
      System.out.println("date1: " + date1);
        
      Month month = currentTime.getMonth();
      int day = currentTime.getDayOfMonth();
      int seconds = currentTime.getSecond();
        
      System.out.println("月: " + month +", 日: " + day +", 秒: " + seconds);
        
      LocalDateTime date2 = currentTime.withDayOfMonth(10).withYear(2012);
      System.out.println("date2: " + date2);
        
      // 12 december 2014
      LocalDate date3 = LocalDate.of(2014, Month.DECEMBER, 12);
      System.out.println("date3: " + date3);
        
      // 22 小时 15 分钟
      LocalTime date4 = LocalTime.of(22, 15);
      System.out.println("date4: " + date4);
        
      // 解析字符串
      LocalTime date5 = LocalTime.parse("20:15:30");
      System.out.println("date5: " + date5);
输出结果:
    当前时间: 2019-04-15T16:55:48.668
    date1: 2019-04-15
    月: APRIL, 日: 15, 秒: 48
    date2: 2012-04-10T16:55:48.668
    date3: 2014-12-12
    date4: 22:15
    date5: 20:15:30
--------------------------------------------------------------------------------
//获取时区时间
// 获取当前时间日期
      ZonedDateTime date1 = ZonedDateTime.parse("2015-12-03T10:15:30+05:30[Asia/Shanghai]");
      System.out.println("date1: " + date1);
        
      ZoneId id = ZoneId.of("Europe/Paris");
      System.out.println("ZoneId: " + id);
        
      ZoneId currentZone = ZoneId.systemDefault();
      System.out.println("当期时区: " + currentZone);
输出结果:
    date1: 2015-12-03T10:15:30+08:00[Asia/Shanghai]
    ZoneId: Europe/Paris
    当期时区: Asia/Shanghai

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值