Java8 新特性之Optional容器类和新时间日期API

简介

  可以将 Optional 看做是包装对象(可能是 null, 也有可能非 null)的容器。当你定义了 一个方法,这个方法返回的对象可能是空,也有可能非空的时候,你就可以考虑用 Optional 来包装它,这也是在 Java 8 被推荐使用的做法。

一、Optional容器类的常用方法

  • Optional.of(T t):创建一个 Optional 实例,of 的参数不能为空
//包装一个User对象,of的参数不能为空
Optional<User> op = Optional.of(new User());
User user = op.get();
  • Optional.empty():创建一个空的 Optional 实例
//创建一个空的
Optional<Object> empty = Optional.empty();
  • Optional.ofNullable(T t):若 t 不为 null,创建 Optional 实例,否则创建空实例
//下面两种创建方式都可以
Optional<User> op1 = Optional.ofNullable(new User());
Optional<Object> op2 = Optional.ofNullable(null);
  • isPresent():判断是否包含值
//判断不是空实例就get
Optional<User> op1 = Optional.ofNullable(new User());
if (op1.isPresent()){
  User user1 = op1.get();
}
  • orElse(T t):如果调用对象包含值(不为空)就返回改值,否则返回 t
//如果为空就自己new一个默认值
Optional<User> op1 = Optional.ofNullable(new User());
User user1 = (User) op2.orElse(new User(18, "cash"));
  • orElseGet(Supplier s):如果调用对象包含值,返回该值,否则返回 s 获取的值
//与上一个方法不同,上一个只能返回值,这个可以有操作
Optional<Object> op2 = Optional.ofNullable(null);
User user2 = (User) op2.orElseGet(() -> new User());
User user3 = (User) op2.orElseGet(User::new);
  • map(Function f):如果有值则对其处理,并返回处理后的 Optional,否则返回 Optional.empty()
//获取年龄
Optional<User> op1 = Optional.ofNullable(new User());
Optional<Integer> opAge = op1.map(e -> e.getAge());
Integer age = opAge.get();
  • flatMap(Function mapper):与 map 类似,但要求返回值必须是 Optional
Optional<User> op1 = Optional.ofNullable(new User());
Optional<Integer> integer = op1.flatMap(e -> Optional.ofNullable(e.getAge()));
Integer age = integer.get();

二、新时间日期API

1.LocalDateTime
//当前时间
LocalDateTime now = LocalDateTime.now();
System.out.println(now); //打印:2020-02-26T11:48:30.807
//构造一个时间
LocalDateTime of = LocalDateTime.of(2020, 2, 26, 12, 55, 30);
System.out.println(of); //打印:2020-02-26T12:55:30
//对日期进行加操作(加1年)
LocalDateTime of1 = of.plusYears(1);
System.out.println(of1); //打印:2021-02-26T12:55:30
//对日期进行减操作(减2个月)
LocalDateTime of2 = of1.minusMonths(2);
System.out.println(of2); //打印:2020-12-26T12:55:30
//获取年份
int year = of2.getYear();
System.out.println(year); //打印:2020
//获取月份
int month = of2.getMonthValue();
System.out.println(month); //打印:12
2.时间戳
//默认获取 UTC 时区时间,有8小时时差
Instant now = Instant.now();
System.out.println(now); //打印:2020-02-26T05:11:23.620Z
//偏移8小时
OffsetDateTime odt = now.atOffset(ZoneOffset.ofHours(8));
System.out.println(odt); //打印:2020-02-26T13:14:25.980+08:00
Instant now = Instant.now();
//转换成毫秒(时间戳)
long l1 = now.toEpochMilli();
//转换成秒
long epochSecond = now.getEpochSecond();
System.out.println(l1);  //打印:1582694335525
System.out.println(epochSecond); //打印:1582694335
3.计算时间差值
  • Duration:计算两个“时间”之间的间隔
Instant now1 = Instant.now();
//睡眠1秒
try {
  Thread.sleep(1000);
} catch (InterruptedException e) {}

Instant now2 = Instant.now();
//计算两个时间的间隔
Duration between = Duration.between(now1, now2);	
//转换成毫秒
long l = between.toMillis();  
System.out.println(l);  //打印:1000
  • Period:计算两个“日期”之间的间隔
LocalDate of = LocalDate.of(2019, 8, 10);
LocalDate now = LocalDate.now();

Period between = Period.between(of, now);

System.out.println(between.getYears());  //打印:0
System.out.println(between.getMonths()); //打印:6
System.out.println(between.getDays());   //打印:16
4.时间矫正器
//计算下个周一的日期
LocalDateTime now = LocalDateTime.now();
LocalDateTime with = now.with(TemporalAdjusters.next(DayOfWeek.FRIDAY));
System.out.println(with);  //打印:2020-02-28T13:37:51.463
//计算下个工作日的时间
LocalDateTime now = LocalDateTime.now();

LocalDateTime time1 = now.with(l -> {
  LocalDateTime time = (LocalDateTime) l;
  DayOfWeek dayOfWeek = time.getDayOfWeek();

  if (dayOfWeek.equals(DayOfWeek.FRIDAY)) {
    return time.plusDays(3);
  } else if (dayOfWeek.equals(DayOfWeek.FRIDAY)) {
    return time.plusDays(2);
  } else {
    return time.plusDays(1);
  }
});

System.out.println(time1); //打印:2020-02-27T13:47:18.883
5.格式化时间/日期
//使用给定的格式化
DateTimeFormatter dtf = DateTimeFormatter.ISO_DATE;
LocalDateTime now = LocalDateTime.now();
System.out.println(now);  //打印:2020-02-26T13:53:08.407
//格式化
String now1 = now.format(dtf);
System.out.println(now1);  //打印:2020-02-26
//使用自定义的格式化
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH时mm分ss秒");
String format = dtf.format(now);
System.out.println(format);  //打印:2020年02月26日 01时56分58秒

//将日期字符串反解析回日期格式
LocalDateTime parse = LocalDateTime.parse(format, dtf);
System.out.println(parse);  //打印:2020-02-26T14:14:18
6.时区
//在生成日期时指定时区
LocalDateTime now = LocalDateTime.now(ZoneId.of("Europe/Tallinn"));
System.out.println(now);
//构建带时区的日期
LocalDateTime now1 = LocalDateTime.now();
ZonedDateTime zonedDateTime = now1.atZone(ZoneId.of("Europe/Tallinn"));
System.out.println(zonedDateTime);
发布了40 篇原创文章 · 获赞 58 · 访问量 3631

猜你喜欢

转载自blog.csdn.net/weixin_40242806/article/details/104512371