JAVA 8 新特性(Lambda 表达式 方法引用 函数式接口 默认方法 Stream Optional 类 新的日期时间 API )

主要特性

  1. Lambda 表达式
  2. 方法引用
  3. 函数式接口
  4. 默认方法
  5. Optional 类
  6. 新的日期时间 API
  7. Stream
  8. Nashorn, JavaScript 引擎(略)

1 Lambda 表达式( a -> a)

Map<String, String> map = new TreeMap<>((o1, o2) -> o1.compareTo(o2));

2 方法引用( :: )

 list.stream().filter(x -> x > 6).forEach(System.out::println);
 Car car = Car.create( Car::new ); //相当于new了一个car
 Stream<Double> stream3 = Stream.generate(Math::random).limit(3);
  Optional<Person> max = personList.stream().max(Comparator.comparingInt(Person::getSalary));

3 函数式接口

  • 函数式接口就是只有一个方法的普通接口。java.lang.Runnableconcurrent.Callable是函数式接口最典型的例子。采用@FunctionalInterface注解 ,函数式接口可被隐式转换为 lambda 表达式。
  • 定义一个函数式接口
@FunctionalInterface
interface MessageService {
 void sayMessage(String message);
}
  • 那么就可以使用Lambda表达式来表示该接口的一个实现(注:JAVA 8 之前一般是用匿名类实现的):
MessageService greetService1 = message -> System.out.println("Hello " + message);

4 接口中可以写默认方法实现(接口定义公共方法)

简单说,默认方法就是接口可以有实现方法,而且不需要实现类去实现其方法。我们只需在方法名前面加个 default 关键字即可实现默认方法。或者直接写静态 static方法实现也可。

对于实现类,处理接口中的方法:可覆盖,或者可直接调用super.do();

5 Optional 类

  • Optional 类解决空指针异常。如果值存在则 isPresent() 方法会返回 true,调用 get() 方法会返回该对象。
//Optional.ofNullable - 允许传递为 null 参数 
Optional<Integer> a = Optional.ofNullable(value1); 

// Optional.of - 如果传递的参数是 null,抛出异常 NullPointerException 
Optional<Integer> b = Optional.of(value2);

// Optional.orElse - 如果值存在,返回它,否则返回默认值 
Integer value1 = a.orElse(new Integer(0));
  • 例子:
//user为null,value也为null,搁在以前,user为null,再判断时会报错的
String value =Optional.ofNullable(user).map(User::getUserName); 

6 日期时间 API

通过发布新的Date-Time API (JSR 310) 来进一步加强对日期与时间的处理。

  • 旧版的 Java 中,日期时间 API 存在诸多问题,其中有

    • 非线程安全
    • 设计很差 java.util.Date、 java.sql.Date 都包含日期。
    • 时区处理麻烦
  • 新版Java 8 在 java.time 包下提供了很多新的 API。以下为两个比较重要的 API:

    • Local(本地) − 简化了日期时间的处理,没有时区的问题。
    • Zoned(时区) − 通过制定的时区处理日期时间。
    LocalDate,LocalTime,LocalDateTime : 时间
    Instant : 时间戳(以Unix元年:1970年1月一日 00:00:00到某个时间时间的毫秒值)
    Duration : 计算两个“时间”之间的间隔
    Period : 计算两个“日期”之间的间隔
    TemporalAdjust :时间校正器
    DateTimeFormatter :格式化时间/日期
    ZonedDate,ZonedTime,ZonedDateTime : 时区
    
  • 不考虑时区

    @Test
    public void test1() {
        // 获取当前的日期时间
        LocalDateTime currentTime = LocalDateTime.now();
        System.out.println("当前时间:" + currentTime);

        LocalDate date1 = currentTime.toLocalDate();
        System.out.println("datel: " + date1);
        Month month = currentTime.getMonth();
        int monthInt = currentTime.getMonthValue();
        int day = currentTime.getDayOfMonth();
        int hour = currentTime.getHour();
        int minute = currentTime.getMinute();
        int seconds = currentTime.getSecond();
        System.out.println("月:" + month + "(" + monthInt + "),日:" + day + ",时:" + hour + ",分:" + minute + ",秒:" + 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);

        // 2022-05-22 22:22:22.000000022
        LocalDateTime date5 = LocalDateTime.of(2022, Month.MAY, 22, 22, 22, 22, 22);
        System.out.println("date5:" + date5);

        // 解析字符串
        LocalTime date6 = LocalTime.parse("22:22");
        System.out.println("date6:" + date6);
        LocalTime date7 = LocalTime.parse("22:22", DateTimeFormatter.ISO_LOCAL_TIME);
        System.out.println("date7:" + date7);
        LocalDateTime date8 = LocalDateTime.parse("2011-12-03 10:15:30:22", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SS"));
        System.out.println("date8:" + date8.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        //  such as '2011-12-03T10:15:30', '2011-12-03T10:15:30+01:00' or '2011-12-03T10:15:30+01:00[Europe/Paris]'.
        LocalDateTime date9 = LocalDateTime.parse("2011-12-03T10:15:30", DateTimeFormatter.ISO_DATE_TIME);
        System.out.println("date9:" + date9);
        /**
         SimpleDateFormat函数语法:
         G 年代标志符
         y 年
         M 月
         d 日
         h 时 在上午或下午 (1~12)
         H 时 在一天中 (0~23)
         m 分
         s 秒
         S 毫秒
         E 星期
         D 一年中的第几天
         F 一月中第几个星期几
         w 一年中第几个星期
         W 一月中第几个星期
         a 上午 / 下午 标记符
         k 时 在一天中 (1~24)
         K 时 在上午或下午 (0~11)
         z 时区
         */

    }
  • 考虑时区:
    @Test
    public void test2() {
        // 获取当前时间日期
        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("Zonerd: " + id);
        ZoneId currentZone = ZoneId.systemDefault();
        System.out.println("当期时区:"+ currentZone);
    }

7 Stream

Java 8 API添加了一个新的抽象称为流Stream,Stream 使用一种类似用 SQL 语句从数据库查询数据的直观方式来提供一种对 Java 集合运算和表达的高阶抽象.

这种风格将要处理的元素集合看作一种流, 流在管道中传输, 并且可以在管道的节点上进行处理, 比如筛选, 排序,聚合等四大管道技术。

在这里插入图片描述

在这里插入图片描述
参考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值