Java8新特性

一、集合

1、HashMap

  • 数组+链表+红黑树

2、HashSet

  • 数组+链表+红黑树

3、ConcurrentHashMap

  • CAS + Synchronized

二、JVM

方法区:永久代PremGen --> 元空间MetaSpace(物理内存)

三、Lambda 表达式

1、从匿名类到Lambda的转换

匿名内部类

//原来的匿名内部类
	@Test
	public void test1(){
		Comparator<String> com = new Comparator<String>(){
			@Override
			public int compare(String o1, String o2) {
				return Integer.compare(o1.length(), o2.length());
			}
		};
		
		TreeSet<String> ts = new TreeSet<>(com);
		
		TreeSet<String> ts2 = new TreeSet<>(new Comparator<String>(){
			@Override
			public int compare(String o1, String o2) {
				return Integer.compare(o1.length(), o2.length());
			}
			
		});
	}
	
	//现在的 Lambda 表达式
	@Test
	public void test2(){
		Comparator<String> com = (x, y) -> Integer.compare(x.length(), y.length());
		TreeSet<String> ts = new TreeSet<>(com);
	}

2、Lambda 表达式的基础语法

Java8中引入了一个新的操作符 “->” 该操作符称为箭头操作符或 Lambda 操作符
箭头操作符将 Lambda 表达式拆分成两部分:

左侧:Lambda 表达式的参数列表
右侧:Lambda 表达式中所需执行的功能, 即 Lambda 体

语法格式一:无参数,无返回值
() -> System.out.println("Hello Lambda!");
语法格式二:有一个参数,并且无返回值
(x) -> System.out.println(x)
语法格式三:若只有一个参数,小括号可以省略不写
x -> System.out.println(x)
语法格式四:有两个以上的参数,有返回值,并且 Lambda 体中有多条语句
Comparator<Integer> com = (x, y) -> {
        System.out.println("函数式接口");
        return Integer.compare(x, y);
     }
语法格式五:若 Lambda 体中只有一条语句, return 和 大括号都可以省略不写
Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
语法格式六:Lambda 表达式的参数列表的数据类型可以省略不写,因为JVM编译器通过上下文推断出,数据类型,即“类型推断”
(Integer x, Integer y) -> Integer.compare(x, y);

上联:左右遇一括号省
下联:左侧推断类型省
横批:能省则省

3、Lambda 表达式需要“函数式接口”的支持

函数式接口:接口中只有一个抽象方法的接口,称为函数式接口。

可以使用注解 @FunctionalInterface 修饰,可以检查是否是函数式接口

四、函数式接口

1、什么是函数式接口?

  • 只包含一个抽象方法的接口
  • 可以通过Lambda表达式来创建该接口的对象。(若 Lambda表达式抛出一个受检异常,那么该异常需要在目标接口的抽象方法_上进行声明)
  • 可以在任意函数式接口上使用@FunctionalInterface注解,这样做可以检查它是否是一个函数式接口,同时javadoc 也会包含一条声明,说明这个接口是一个函数式接口。

2、自定义函数式接口

@FunctionalInterface
public interface MyNumber {
  public double getValue();
}

函数式接口中使用泛型:

@FunctionalInterface
public interface MyFunc<T> {
  public T getValue(T t);
}

作为参数传递Lambda表达式:

public String toUpperString (MyFunc<String> mf,String str) {
	return mf .getValue(str);
}
String newStr = toUpperString(
  (str) -> str.toUpperCase(),"abcdef");
System.out.println(newStr);

为了将Lambda 表达式作为参数传递,接收Lambda表达式的参数类型必须是与该Lambda表达式兼容的函数式接口的类型。

3、Java8 内置的四大核心函数式接口

image-20210619141916206

  • Consumer : 消费型接口
    • void accept(T t);
  • Supplier : 供给型接口
    • T get();
  • Function<T, R> : 函数型接口
    • R apply(T t);
  • Predicate : 断言型接口
    • boolean test(T t);
Consumer 消费型接口
@Test
public void test1(){
  happy(10000, (m) -> System.out.println("去超市消费:" + m + "元"));
} 

public void happy(double money, Consumer<Double> con){
  con.accept(money);
}
Supplier 供给型接口
@Test
public void test2(){
  List<Integer> numList = getNumList(10, () -> (int)(Math.random() * 100));

  for (Integer num : numList) {
    System.out.println(num);
  }
}

//需求:产生指定个数的整数,并放入集合中
public List<Integer> getNumList(int num, Supplier<Integer> sup){
  List<Integer> list = new ArrayList<>();

  for (int i = 0; i < num; i++) {
    Integer n = sup.get();
    list.add(n);
  }

  return list;
}
Function<T, R> 函数型接口
@Test
public void test3(){
  String newStr = strHandler("\t\t\t 我大尚硅谷威武   ", (str) -> str.trim());
  System.out.println(newStr);

  String subStr = strHandler("我大尚硅谷威武", (str) -> str.substring(2, 5));
  System.out.println(subStr);
}

//需求:用于处理字符串
public String strHandler(String str, Function<String, String> fun){
  return fun.apply(str);
}
Predicate 断言型接口
@Test
public void test4(){
  List<String> list = Arrays.asList("Hello", "atguigu", "Lambda", "www", "ok");
  List<String> strList = filterStr(list, (s) -> s.length() > 3);

  for (String str : strList) {
    System.out.println(str);
  }
}

//需求:将满足条件的字符串,放入集合中
public List<String> filterStr(List<String> list, Predicate<String> pre){
  List<String> strList = new ArrayList<>();

  for (String str : list) {
    if(pre.test(str)){
      strList.add(str);
    }
  }

  return strList;
}

五、方法引用与构造器引用

1、方法引用

当要传递给Lambda体的操作,已经有实现的方法了,可以使用方法引用!
(实现抽象方法的参数列表,必须与方法引用方法的参数列表保持一致! )
方法引用:使用操作符“::”将方法名和对象或类的名字分隔开来。
如下三种主要使用情况:

  • 对象::实例方法
  • 类::静态方法
  • 类::实例方法
1.1 对象的引用 :: 实例方法名
@Test
public void test1(){
  PrintStream ps = System.out;
  Consumer<String> con = (str) -> ps.println(str);
  con.accept("Hello World!");

  System.out.println("--------------------------------");

  Consumer<String> con2 = ps::println;
  con2.accept("Hello Java8!");

  Consumer<String> con3 = System.out::println;
}
@Test
public void test2(){
  Employee emp = new Employee(101, "张三", 18, 9999.99);

  Supplier<String> sup = () -> emp.getName();
  System.out.println(sup.get());

  System.out.println("----------------------------------");

  Supplier<String> sup2 = emp::getName;
  System.out.println(sup2.get());
}
1.2 类名 :: 静态方法名
@Test
	public void test3(){
		BiFunction<Double, Double, Double> fun = (x, y) -> Math.max(x, y);
		System.out.println(fun.apply(1.5, 22.2));
		
		System.out.println("----------------------------------");
		
		BiFunction<Double, Double, Double> fun2 = Math::max;
		System.out.println(fun2.apply(1.2, 1.5));
	}
@Test
public void test4(){
  Comparator<Integer> com = (x, y) -> Integer.compare(x, y);

  System.out.println("-------------------------------------");

  Comparator<Integer> com2 = Integer::compare;
}
1.3 类名 :: 实例方法名

注意:当需要引用方法的第-一个参数是调用对象,并且第二个参数是需要引
用方法的第二个参数(或无参数)时: ClassName: :methodName .

@Test
public void test5(){
  BiPredicate<String, String> bp = (x, y) -> x.equals(y);
  System.out.println(bp.test("abcde", "abcde"));

  System.out.println("---------------------------------------");

  BiPredicate<String, String> bp2 = String::equals;
  System.out.println(bp2.test("abc", "abc"));

  System.out.println("---------------------------------------");


  Function<Employee, String> fun = (e) -> e.show();
  System.out.println(fun.apply(new Employee()));

  System.out.println("---------------------------------------");

  Function<Employee, String> fun2 = Employee::show;
  System.out.println(fun2.apply(new Employee()));

}

2、构造器引用

格式: ClassName::new
与函数式接口相结合,自动与函数式接口中方法兼容。可以把构造器引用赋值给定义的方法,与构造器参数列表要与接口中抽象方法的参数列表一致!

示例:

@Test
public void test6(){
  Supplier<Employee> sup = () -> new Employee();
  System.out.println(sup.get());

  System.out.println("------------------------------------");

  Supplier<Employee> sup2 = Employee::new;
  System.out.println(sup2.get());
}
@Test
public void test7(){
  Function<String, Employee> fun = Employee::new;

  BiFunction<String, Integer, Employee> fun2 = Employee::new;
}

3、数组引用

格式: type[]::new

示例:

@Test
public void test8(){
  Function<Integer, String[]> fun = (args) -> new String[args];
  String[] strs = fun.apply(10);
  System.out.println(strs.length);

  System.out.println("--------------------------");

  Function<Integer, Employee[]> fun2 = Employee[] :: new;
  Employee[] emps = fun2.apply(20);
  System.out.println(emps.length);
}

六、Stream

1、什么是Stream?

Java8中有两大最为重要的改变。第一个是Lambda表达式;另外一个则是Stream API(java. util. stream. *)。
Stream是Java8中处理集合的关键抽象概念,它可以指定你希望对集合进行的操作,可以执行非常复杂的查找、过滤和映射数据等操作。使用Stream API对集合数据进行操作,就类似于使用SQL 执行的数据库查询。也可以使用Stream API来并行执行操作。简而言之,Stream API提供了一-种高效且易于使用的处理数据的方式。

流(Stream)到底是什么呢?
是数据渠道,用于操作数据源(集合、数组等)所生成的元素序列。
“集合讲的是数据,流讲的是计算!

注意:
①Stream自己不会存储元素。
②Stream不会改变源对象。相反,他们会返回一个持有结果的新Stream。
③Stream操作是延迟执行的。这意味着他们会等到需要结果的时候才执行。

2、Stream的操作三个步骤

  • 创建Stream
    • 一个数据源(如:集合、数组) ,获取一个流
  • 中间操作
    • 一个中间操作链,对数据源的数据进行处理
  • 终止操作(终端操作)
    • 一个终止操作,执行中间操作链,并产生结果

image-20210619144504460

2.1 创建Stream

Java8中的Collection接口被扩展,提供了两个获取流的方法:

  • default Stream stream() :返回一个顺序流
  • default Stream parallelStream() :返回一个并行流
由数组创建流

Java8 中的Arrays的静态方法stream()可以获取数组流:

static Stream stream(T[] array):返回一个流

重载形式,能够处理对应基本类型的数组:

  • public static IntStream stream(int[] array)
  • public static LongStream stream(long[] array)
  • public static DoubleStream stream (double[] array)
由值创建流

可以使用静态方法Stream.of(), 通过显示值创建一个流。它可以接收任意数量的参数。
public static Stream of(T… values) :返回一个流

由函数创建流:创建无限流

可以使用静态方法Stream. iterate()和Stream. generate() ,创建无限流。

  • 迭代
    • public static Stream iterate(final T seed, final UnaryOperator f)
  • 生成
    • public static Stream generate (Supplier s) :

示例:

@Test
public void test1(){
  //1. Collection 提供了两个方法  stream() 与 parallelStream()
  List<String> list = new ArrayList<>();
  Stream<String> stream = list.stream(); //获取一个顺序流
  Stream<String> parallelStream = list.parallelStream(); //获取一个并行流

  //2. 通过 Arrays 中的 stream() 获取一个数组流
  Integer[] nums = new Integer[10];
  Stream<Integer> stream1 = Arrays.stream(nums);

  //3. 通过 Stream 类中静态方法 of()
  Stream<Integer> stream2 = Stream.of(1,2,3,4,5,6);

  //4. 创建无限流
  //迭代
  Stream<Integer> stream3 = Stream.iterate(0, (x) -> x + 2).limit(10);
  stream3.forEach(System.out::println);

  //生成
  Stream<Double> stream4 = Stream.generate(Math::random).limit(2);
  stream4.forEach(System.out::println);

}
2.2 Stream的中间操作

多个中间操作可以连接起来形成一个流水线,除非流水线上触发终止操作,否则中间操作不会执行任何的处理!而在终止操作时一次性全部处理,称为“惰性求值”

筛选与切片

image-20210619145542484

示例:

//内部迭代:迭代操作 Stream API 内部完成
@Test
public void test2(){
  //所有的中间操作不会做任何的处理
  Stream<Employee> stream = emps.stream()
    .filter((e) -> {
      System.out.println("测试中间操作");
      return e.getAge() <= 35;
    });

  //只有当做终止操作时,所有的中间操作会一次性的全部执行,称为“惰性求值”
  stream.forEach(System.out::println);
}
	
	//外部迭代
@Test
public void test3(){
  Iterator<Employee> it = emps.iterator();

  while(it.hasNext()){
    System.out.println(it.next());
  }
}
	
@Test
public void test4(){
  emps.stream()
    .filter((e) -> {
      System.out.println("短路!"); // &&  ||
      return e.getSalary() >= 5000;
    }).limit(3)
    .forEach(System.out::println);
}
	
@Test
public void test5(){
  emps.parallelStream()
    .filter((e) -> e.getSalary() >= 5000)
    .skip(2)
    .forEach(System.out::println);
}
	
@Test
public void test6(){
  emps.stream()
    .distinct()
    .forEach(System.out::println);
}
映射

image-20210619150012450

示例:

@Test
public void test1(){
  Stream<String> str = emps.stream()
    .map((e) -> e.getName());

  System.out.println("---------------------------------------");

  List<String> strList = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee");

  Stream<String> stream = strList.stream()
    .map(String::toUpperCase);

  stream.forEach(System.out::println);

  Stream<Stream<Character>> stream2 = strList.stream()
    .map(TestStreamAPI1::filterCharacter);

  stream2.forEach((sm) -> {
    sm.forEach(System.out::println);
  });

  System.out.println("---------------------------------------");

  Stream<Character> stream3 = strList.stream()
    .flatMap(TestStreamAPI1::filterCharacter);

  stream3.forEach(System.out::println);
}

public static Stream<Character> filterCharacter(String str){
  List<Character> list = new ArrayList<>();

  for (Character ch : str.toCharArray()) {
    list.add(ch);
  }

  return list.stream();
}
排序

image-20210619150246719

示例:

@Test
public void test2(){
  emps.stream()
    .map(Employee::getName)
    .sorted()
    .forEach(System.out::println);

  System.out.println("------------------------------------");

  emps.stream()
    .sorted((x, y) -> {
      if(x.getAge() == y.getAge()){
        return x.getName().compareTo(y.getName());
      }else{
        return Integer.compare(x.getAge(), y.getAge());
      }
    }).forEach(System.out::println);
}
2.3 Stream的终止操作

终端操作会从流的流水线生成结果。其结果可以是任何不是流的值,例如: List、 Integer, 甚至是void 。

查找与匹配

image-20210619150617947

示例:

@Test
public void test1(){
  boolean bl = emps.stream()
    .allMatch((e) -> e.getStatus().equals(Status.BUSY));

  System.out.println(bl);

  boolean bl1 = emps.stream()
    .anyMatch((e) -> e.getStatus().equals(Status.BUSY));

  System.out.println(bl1);

  boolean bl2 = emps.stream()
    .noneMatch((e) -> e.getStatus().equals(Status.BUSY));

  System.out.println(bl2);
}

@Test
public void test2(){
  Optional<Employee> op = emps.stream()
    .sorted((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()))
    .findFirst();

  System.out.println(op.get());

  System.out.println("--------------------------------");

  Optional<Employee> op2 = emps.parallelStream()
    .filter((e) -> e.getStatus().equals(Status.FREE))
    .findAny();

  System.out.println(op2.get());
}
计算

image-20210619150756726

示例:

@Test
public void test3(){
  long count = emps.stream()
    .filter((e) -> e.getStatus().equals(Status.FREE))
    .count();

  System.out.println(count);

  Optional<Double> op = emps.stream()
    .map(Employee::getSalary)
    .max(Double::compare);

  System.out.println(op.get());

  Optional<Employee> op2 = emps.stream()
    .min((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()));

  System.out.println(op2.get());
}

//注意:流进行了终止操作后,不能再次使用
@Test
public void test4(){
  Stream<Employee> stream = emps.stream()
    .filter((e) -> e.getStatus().equals(Status.FREE));

  long count = stream.count();

  stream.map(Employee::getSalary)
    .max(Double::compare);
}
规约

image-20210619151119019

示例:

@Test
public void test1(){
  List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);

  Integer sum = list.stream()
    .reduce(0, (x, y) -> x + y);

  System.out.println(sum);

  System.out.println("---------------------------------------");

  Optional<Double> op = emps.stream()
    .map(Employee::getSalary)
    .reduce(Double::sum);

  System.out.println(op.get());
}

//需求:搜索名字中 “六” 出现的次数
@Test
public void test2(){
  Optional<Integer> sum = emps.stream()
    .map(Employee::getName)
    .flatMap(TestStreamAPI1::filterCharacter)
    .map((ch) -> {
      if(ch.equals('六'))
        return 1;
      else 
        return 0;
    }).reduce(Integer::sum);

  System.out.println(sum.get());
}
收集

image-20210619151405774

Collector接口中方法的实现决定了如何对流执行收集操作(如收集到List、Set、Map)。但是Collectors 实用类提供了很多静态方法,可以方便地创建常见收集器实例,具体方法与实例如下表:

image-20210619151454666

image-20210619151540805

示例:

@Test
public void test3(){
  List<String> list = emps.stream()
    .map(Employee::getName)
    .collect(Collectors.toList());

  list.forEach(System.out::println);

  System.out.println("----------------------------------");

  Set<String> set = emps.stream()
    .map(Employee::getName)
    .collect(Collectors.toSet());

  set.forEach(System.out::println);

  System.out.println("----------------------------------");

  HashSet<String> hs = emps.stream()
    .map(Employee::getName)
    .collect(Collectors.toCollection(HashSet::new));

  hs.forEach(System.out::println);
}

@Test
public void test4(){
  Optional<Double> max = emps.stream()
    .map(Employee::getSalary)
    .collect(Collectors.maxBy(Double::compare));

  System.out.println(max.get());

  Optional<Employee> op = emps.stream()
    .collect(Collectors.minBy((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())));

  System.out.println(op.get());

  Double sum = emps.stream()
    .collect(Collectors.summingDouble(Employee::getSalary));

  System.out.println(sum);

  Double avg = emps.stream()
    .collect(Collectors.averagingDouble(Employee::getSalary));

  System.out.println(avg);

  Long count = emps.stream()
    .collect(Collectors.counting());

  System.out.println(count);

  System.out.println("--------------------------------------------");

  DoubleSummaryStatistics dss = emps.stream()
    .collect(Collectors.summarizingDouble(Employee::getSalary));

  System.out.println(dss.getMax());
}

//分组
@Test
public void test5(){
  Map<Status, List<Employee>> map = emps.stream()
    .collect(Collectors.groupingBy(Employee::getStatus));

  System.out.println(map);
}

//多级分组
@Test
public void test6(){
  Map<Status, Map<String, List<Employee>>> map = emps.stream()
    .collect(Collectors.groupingBy(Employee::getStatus, Collectors.groupingBy((e) -> {
      if(e.getAge() >= 60)
        return "老年";
      else if(e.getAge() >= 35)
        return "中年";
      else
        return "成年";
    })));

  System.out.println(map);
}

//分区
@Test
public void test7(){
  Map<Boolean, List<Employee>> map = emps.stream()
    .collect(Collectors.partitioningBy((e) -> e.getSalary() >= 5000));

  System.out.println(map);
}

//
@Test
public void test8(){
  String str = emps.stream()
    .map(Employee::getName)
    .collect(Collectors.joining("," , "----", "----"));

  System.out.println(str);
}

@Test
public void test9(){
  Optional<Double> sum = emps.stream()
    .map(Employee::getSalary)
    .collect(Collectors.reducing(Double::sum));

  System.out.println(sum.get());
}

3、并行流与串行流

并行流就是把一个内容分成多个数据块,并用不同的线程分别处理每个数据块的流。
Java 8中将并行进行了优化,我们可以很容易的对数据进行并行操作。Stream API可以声明性地通过parallel() 与sequential()在并行流与顺序流之间进行切换。

3.1 Fork/Join框架

Fork/Join 框架:就是在必要的情况下,将-一个大任务,进行拆分(fork)成若干个小任务(拆到不可再拆时),再将一个个的小任务运算的结果进行join汇总.

image-20210619152216122

3.2 Fork/ Join框架与传统线程池的区别

采用“工作窃取”模式(work-stealing) :
当执行新的任务时它可以将其拆分分成更小的任务执行,并将小任务加到线程队列中,然后再从一个随机线程的队列中偷一个并把它放在自己的队列中。

相对于一般的线程池实现,fork/join框架的优势体现在对其中包含的任务的处理方式上.在一般的线程池中,如果一个线程正在执行的任务由于某些原因无法继续运行,那么该线程会处于等待状态.而在fork/ join框架实现中,如果某个子问题由于等待另外一个子问题的完成而无法继续运行.那么处理该子问题的线程会主动寻找其他尚未运行的子问题来执行.这种方式减少了线程的等待时间,提高了性能.

3.3 对比与测试
import java.util.concurrent.RecursiveTask;

public class ForkJoinCalculate extends RecursiveTask<Long>{

  /**
	 * 
	 */
  private static final long serialVersionUID = 13475679780L;

  private long start;
  private long end;

  private static final long THRESHOLD = 10000L; //临界值

  public ForkJoinCalculate(long start, long end) {
    this.start = start;
    this.end = end;
  }

  @Override
  protected Long compute() {
    long length = end - start;

    if(length <= THRESHOLD){
      long sum = 0;

      for (long i = start; i <= end; i++) {
        sum += i;
      }

      return sum;
    }else{
      long middle = (start + end) / 2;

      ForkJoinCalculate left = new ForkJoinCalculate(start, middle);
      left.fork(); //拆分,并将该子任务压入线程队列

      ForkJoinCalculate right = new ForkJoinCalculate(middle+1, end);
      right.fork();

      return left.join() + right.join();
    }

  }

}
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;

import org.junit.Test;

public class TestForkJoin {

  // 方式1:传统的for循环遍历
  @Test
  public void test1(){
    long start = System.currentTimeMillis();

    long sum = 0L;

    for (long i = 0L; i <= 10000000000L; i++) {
      sum += i;
    }

    System.out.println(sum);

    long end = System.currentTimeMillis();

    System.out.println("耗费的时间为: " + (end - start)); //5233ms
  }
  // 方式2:使用fork-join框架
  @Test
  public void test2(){
    long start = System.currentTimeMillis();

    ForkJoinPool pool = new ForkJoinPool();
    ForkJoinTask<Long> task = new ForkJoinCalculate(0L, 10000000000L);

    long sum = pool.invoke(task);
    System.out.println(sum);

    long end = System.currentTimeMillis();

    System.out.println("耗费的时间为: " + (end - start)); //1780ms
  }
  // 方式3:使用stream并行流
  @Test
  public void test3(){
    long start = System.currentTimeMillis();

    Long sum = LongStream.rangeClosed(0L, 10000000000L)
      .parallel()
      .sum();

    System.out.println(sum);

    long end = System.currentTimeMillis();

    System.out.println("耗费的时间为: " + (end - start)); //1248ms
  }

}

七、Optional类

Optional类(java. util. Optional)是一个容器类,代表一个值存在或不存在,
原来用null表示一个值不存在,现在Optional 可以更好的表达这个概念。并且
可以避免空指针异常。

1、常用方法

  • Optional.of(T t) :创建一个Optional 实例
  • Optional.empty() :创建一个空的Optional 实例
  • Optional.ofNullable(T t):若t不为null, 创建Optional实例,否则创建空实例
  • isPresent() :判断是否包含值
  • orElse(T t):如果调用对象包含值,返回该值,否则返回t
  • orElseGet (Supplier s) : 如果调用对象包含值,返回该值,否则返回s获取的值
  • map (Function f):如果有值对其处理,并返回处理后的Optional,否则返回Optional. empty ()
  • flatMap (Function mapper) :与map类似,要求返回值必须是0ptional

2、使用示例

@Test
public void test1(){
  Optional<Employee> op = Optional.of(new Employee());
  Employee emp = op.get();
  System.out.println(emp);
}

@Test
public void test2(){
  Optional<Employee> op = Optional.ofNullable(null);
  System.out.println(op.get());
  //		Optional<Employee> op = Optional.empty();
  //		System.out.println(op.get());
}

@Test
public void test3(){
  Optional<Employee> op = Optional.ofNullable(new Employee());

  if(op.isPresent()){
    System.out.println(op.get());
  }

  Employee emp = op.orElse(new Employee("张三"));
  System.out.println(emp);

  Employee emp2 = op.orElseGet(() -> new Employee());
  System.out.println(emp2);
}

@Test
public void test4(){
  Optional<Employee> op = Optional.of(new Employee(101, "张三", 18, 9999.99));

  Optional<String> op2 = op.map(Employee::getName);
  System.out.println(op2.get());

  Optional<String> op3 = op.flatMap((e) -> Optional.of(e.getName()));
  System.out.println(op3.get());
}

八、接口中的默认方法与静态方法

1、接口中的默认方法

Java 8中允许接口中包含具有具体实现的方法,该方法称为“默认方法”,默认方法使用default 关键字修饰。

接口默认方法的”类优先”原则

若一个接口中定义了一个默认方法,而另外一个父类或接口中又定义了一个同名的方法时

  • 选择父类中的方法。如果一个父类提供了具体的实现,那么接口中具有相同名称和参数的默认方法会被忽略。
  • 接口冲突。如果一个父接口提供一一个默认方法,而另一个接口也提供了一个具有相同名称和参数列表的方法(不管方法是否是默认方法),那么必须覆盖该方法来解决冲突

2、接口中的静态方法

Java8中,接口中允许添加静态方法。

3、示例

public interface MyInterface {

  default String getName(){
    return "呵呵呵";
  }

  public static void show(){
    System.out.println("接口中的静态方法");
  }

}

九、新时间日期API

1、使用LocalDate、LocalTime、LocalDateTime

LocalDate、LocalTime、 LocalDateTime 类的实例是不可变的对象,分别表示使用ISO-8601日历系统的日期、时间、日期和时间。它们提供了简单的日期或时间,并不包含当前的时间信息。也不包含与时区相关的信息。

image-20210619170733729

示例:

@Test
public void test1(){
  LocalDateTime ldt = LocalDateTime.now();
  System.out.println(ldt);

  LocalDateTime ld2 = LocalDateTime.of(2021, 6, 19, 10, 10, 10);
  System.out.println(ld2);

  LocalDateTime ldt3 = ld2.plusYears(20);
  System.out.println(ldt3);

  LocalDateTime ldt4 = ld2.minusMonths(2);
  System.out.println(ldt4);

  System.out.println(ldt.getYear());
  System.out.println(ldt.getMonthValue());
  System.out.println(ldt.getDayOfMonth());
  System.out.println(ldt.getHour());
  System.out.println(ldt.getMinute());
  System.out.println(ldt.getSecond());
}

2、Instant时间戳

用于“时间戳”的运算。它是以Unix元年(传统的设定为UTC时区1970年1月1日午夜时分)开始所经历的描述进行运算

示例:

@Test
public void test2(){
  Instant ins = Instant.now();  //默认使用 UTC 时区
  System.out.println(ins);

  OffsetDateTime odt = ins.atOffset(ZoneOffset.ofHours(8));
  System.out.println(odt);

  System.out.println(ins.getNano());

  Instant ins2 = Instant.ofEpochSecond(5);
  System.out.println(ins2);
}

3、Duration和Period

  • Duration:用于计算两个‘时间”间隔
  • Period:用于计算两个“日期”间隔

示例:

@Test
public void test3(){
  Instant ins1 = Instant.now();

  System.out.println("--------------------");
  try {
    Thread.sleep(1000);
  } catch (InterruptedException e) {
  }

  Instant ins2 = Instant.now();

  System.out.println("所耗费时间为:" + Duration.between(ins1, ins2));

  System.out.println("----------------------------------");

  LocalDate ld1 = LocalDate.now();
  LocalDate ld2 = LocalDate.of(2011, 1, 1);

  Period pe = Period.between(ld2, ld1);
  System.out.println(pe.getYears());
  System.out.println(pe.getMonths());
  System.out.println(pe.getDays());
}

3、日期的操纵

  • TemporalAdjuster:时间校正器。有时我们可能需要获取例如:将日期调整到“下个周日”等操作。
  • TemporalAdjusters: 该类通过静态方法提供了大量的常用TemporalAdjuster的实现。

示例:

@Test
public void test4(){
  LocalDateTime ldt = LocalDateTime.now();
  System.out.println(ldt); // 2021-06-19T17:15:37.764

  LocalDateTime ldt2 = ldt.withDayOfMonth(10);
  System.out.println(ldt2); // 2021-06-10T17:15:37.764

  LocalDateTime ldt3 = ldt.with(TemporalAdjusters.next(DayOfWeek.SUNDAY));
  System.out.println(ldt3); // 2021-06-20T17:15:37.764

  //自定义:下一个工作日
  LocalDateTime ldt5 = ldt.with((l) -> {
    LocalDateTime ldt4 = (LocalDateTime) l;

    DayOfWeek dow = ldt4.getDayOfWeek();

    if(dow.equals(DayOfWeek.FRIDAY)){
      return ldt4.plusDays(3);
    }else if(dow.equals(DayOfWeek.SATURDAY)){
      return ldt4.plusDays(2);
    }else{
      return ldt4.plusDays(1);
    }
  });

  System.out.println(ldt5); // 2021-06-21T17:15:37.764

}

4、解析与格式化

java.time.format.DateTimeFormatter类:该类提供了三种格式化方法:

  • 预定义的标准格式
  • 语言环境相关的格式
  • 自定义的格式

示例:

@Test
public void test5(){

  DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss E");

  LocalDateTime ldt = LocalDateTime.now();
  String strDate = ldt.format(dtf);

  System.out.println(strDate); // 2021年06月19日 17:18:17 星期六

  LocalDateTime newLdt = ldt.parse(strDate, dtf);
  System.out.println(newLdt); // 2021-06-19T17:18:17
}

5、时区的处理

Java8中加入了对时区的支持,带时区的时间为分别为:
ZonedDate、ZonedTime、 ZonedDateTime

其中每个时区都对应着ID,地区ID都为“{区 域}/{城市}”的格式,
例如: Asia/Shanghai 等

  • Zoneld:该类中包含了所有的时区信息
  • getAvailableZonelds() :可以获取所有时区时区信息
  • of(id):用指定的时区信息获取Zoneld对象

示例:

@Test
public void test6(){
  //获取所有时区
  Set<String> set = ZoneId.getAvailableZoneIds();
  set.forEach(System.out::println);
}
@Test
public void test7(){
  LocalDateTime ldt = LocalDateTime.now(ZoneId.of("Asia/Shanghai"));
  System.out.println(ldt); // 2021-06-19T17:21:24.815

  ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("US/Pacific"));
  System.out.println(zdt); // 2021-06-19T02:21:24.817-07:00[US/Pacific]
}

6、与传统日期处理的转换

image-20210619172523920

十、重复注解与类型注解

Java 8对注解处理提供了两点改进:可重复的注解及可用于类型的注解。

image-20210619172919408

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值