JDK8新特性以及操作

1、hash

hashMap,hashSet内部结构变化。

之前是链表的结构,变成了链表加红黑树的结构

map的结构全部进行了优化

2、内存结构

栈,堆,方法区,永久区

永久区就是堆的一部分,方法区是永久区的一部分(在一般情况下会单独分出来),在许多种jdk中已经没有永久区,方法区也从永久区中剥离出来

在java8去掉永久区,使用MetaSpace(元空间)直接使用物理内存

jvm进行调优时参数变化

MetaspaceSize

MaxMetaspaceSize

3、Lambda

3.1 表达式基础语法

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

左侧:Lambda表达式的参数列表

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

语法格式一:无参数,无返回值

​ ()->System.out.println(“hello Lambda!”);

 @Test
    public  void lambda01(){
        //传统的方式
        Runnable runnable=new Runnable() {
            @Override
            public void run() {
                System.out.println("Hello word");
            }
        };
        runnable.run();

        System.out.println("--------------");
        //Lambda表达式
       Runnable runnable1=()-> System.out.println("Hello lambda!");
       runnable1.run();
    }

语法格式二:有一个参数,无返回值

​ (x)->System.out.println(x);

 @Test
    public  void lambda02(){
        Consumer consumer=(x)-> System.out.println(x);
        consumer.accept("Lambda就是这么的强大");
    }

语法格式三:若只有有一个参数,小括号可以不写

​ x->System.out.println(x);

 @Test
    public  void lambda03(){
        Consumer consumer=x-> System.out.println(x);
        consumer.accept("Lambda就是这么的强大");
    }

语法格式四:有两个以上的参数,有返回值,并且Lambda体中有多条语句。Lambda体必须用{}大括号括起来

 @Test
    public  void lambda04(){
        Comparator<Integer> com=(x,y)->{
            System.out.println("就是这么酷");
            return Integer.compare(x,y);
        };
    }

语法格式五:若Lambda体中只有一条语句,大括号和return都可以省略不写

 @Test
    public  void lambda05(){
        Comparator<Integer> com=(x,y)-> Integer.compare(x,y);
    }

语法格式六:lambda表达式的参数列表数据类型可以省略不写,因为JVM编译器通过上下文推断出数据类型,即"类型推断"

左右遇一括号省

左侧推断类型省

3.2 Lambda表达式使用条件

Lambda表达式需要函数式接口的支持

**函数式接口:**接口中只有一个抽象方法的接口,称为函数式接口,可以使用注解@FunctionalInterface修饰,可以检查是否是函数式接口

练习1

@FunctionalInterface
public interface Myfun {
    public  Integer getValue(Integer num);
}
 //需求对一个数进行运算
    @Test
    public void lambda06(){

        Integer opertion = opertion(200, x -> x * x);
        System.out.println(opertion);
    }

    public Integer opertion(Integer number,Myfun myfun){
        return  myfun.getValue(number);
    }

练习二

 List<Employee> employees= Arrays.asList(
            new Employee("张三",13,1999.99),
            new Employee("李四",154,1999.99),
            new Employee("王五",45,199858),
            new Employee("赵六",36,1999)
    );

    @Test
    public  void lambda07(){
        Collections.sort(employees,(e1,e2)->{
            if(e1.getAge().equals(e2.getAge())){
                return e1.getName().compareTo(e2.getName());
            }else {
                return Integer.compare(e1.getAge(),e2.getAge());
            }
        });
        for (Employee employee:employees){
            System.out.println(employee);
        }
    }

4、核心函数式接口

java8内置的四大核心函数式接口

Consumer<T>:消费型接口

​ void accept(T t);

Supplier<T>:供给型接口

​ T get();

Function<T,R>:函数型接口

​ 传过去一个值,返回另一个值,在泛型中进行定义返回值和参数的类型

​ R apply(T t):

Predicate<T>:断言型接口

​ boolean test(T t);

4.1 Consumer

参数类型:T

返回类型:void

用法:对类型为T的对象应用操作,包含方法:void accept(T t)

 @Test
    public  void lambda10(){
        happy(100,m-> System.out.println("每次消费"+m));
    }
    public void happy(double money,Consumer consumer){

        consumer.accept(money);
    }

4.2Supplier<T>

参数类型:无

返回类型:T

用途:返回类型为T的对象,包含方法:T get();

//产生10个随机数
    @Test
    public void test() {
        Supplier<List> supplier=()->{
            List<Integer> arrayList =new ArrayList<>();
            for (int i=0; i<10;i++){
                int num=(int)(Math.random()*100);
                arrayList.add(num);
            }
            return arrayList;
        };

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

或者

@Test
public void test2() {
        List<Integer> numList = getNumList(10, () -> (int) (Math.random() * 100));
        System.out.println(numList);
    }

public List<Integer> getNumList(int num,Supplier<Integer> supplier){
        List<Integer> list=new ArrayList<>();
        for (int i=0;i<num;i++){
            Integer integer = supplier.get();
            list.add(1);
        }
        return list;
    }

4.3 Function<T,R>

参数类型:T

返回类型:R

用途:对类型为T的对象应用操作,并返回结果。结果是R类型的对象。包含方法:R apply(T t);

 @Test
    public  void  test04(){
        String s = paseString("how are you ? yes i am fine.", (x) -> x.toUpperCase());
        System.out.println(s);
    }

    public String paseString(String str,Function<String,String> function){
        return  function.apply(str);
    }

4.4 Predicate<T>

参数类型:T

返回类型:boolean

用途:确定类型为T的对象是否满足某约束,并返回boolean 值。包含方法boolean test(T t);

 @Test
    public  void  
    +test05(){
        List<String> list= Arrays.asList("hellp","lp","nihaojiushi ","ul","power");
        List<String> list1 = filterStr(list, (x) -> x.length() > 3);
        System.out.println(list1);
    }
    public  List<String> filterStr(List<String> list, Predicate<String> stringPredicate) {
        List<String> list1=new LinkedList<>();
        for (String s:list){
            if (stringPredicate.test(s)){
                list1.add(s);
            }
        }
        return list1;
    }

4.5 其他接口

函数式接口 参数类型 返回类型 用途
BigFunction<T,U,R> T,U R 对类型为T,U参数应用操作,返回R类型的结果。包含方法为 R apply(T t,U u);
UnaryOperator<T>(Function子接口) T T 对类型为T的对象进行一元运算,并返回T类型的结果。包含方法为T apply(T t);
BinaryOperator<T>(BiFunction 子接) T, T T 对类型为T的对象进行二元运算,并返回T类型的结果。包含方法为T apply(T t1, T t2)
BiConsumer<T,U> T, U void 对类型为T, U 参数应用操作。包含方法为void accept(T t, U u)
ToIntFunction<T>
ToLongFunction<T>
ToDoubleFunction<T>
T int
long
double
分 别 计 算 int 、 long 、double、值的函数
IntFunction
LongFunction
DoubleFunction
int
long
double
R 参数分别为int、long、double 类型的函数

5、方法引用

若Lambda表达体中的内容有方法已经实现了,我们可以使用“方法引用”(可以理解为方法引用是Lambda表达式的另一个表现形式)

主要语法:

对象::实例方法名

类::静态方法名

类::实例方法名

注意:

①Lambda体中调用方法的参数列表和返回值类型,要与函数式接口中的抽象方法的函数列表和返回值类型保持一致

②若Lambda参数列表中的第一个参数是实例方法的调用者,而第二个参数是实例方法的参数时,可以使用ClassName::method

5.1 对象::实例方法名

  @Test
    public  void  test06(){
        //Lambda表达式
        Consumer<String> consumer=(x)-> System.out.println(x);
        consumer.accept("hello");
        //对象::实例方法名
        Consumer<String> consumer1= System.out::println;
        consumer1.accept("me too");
    }

5.2 类::静态方法名

  @Test
    public  void  test07(){
        //Lambda表达式
        Comparator<Integer> comparator=(x,y)->Integer.compare(x,y);
        
        //类::静态方法名
        Comparator<Integer> com= Integer::compare;
        
    }

5.3 类::实例方法名

@Test
    public  void  test08(){
        //Lambda表达式
        BiPredicate<String,String> bp=(x,y)->x.equals(y);
        boolean test = bp.test("hello", "hello");
        System.out.println(test);
        //类::实例方法名
        BiPredicate<String,String> bp1= String::equals;
        boolean test1 = bp1.test("hi", "hello");
        System.out.println(test1);
    }

6、构造器引用

格式:

ClassName::new

需要调用的构造器的参数列表要与函数式接口中的抽象方法的参数列表一致

根据函数式抽象方法的列表来决定构造器的使用,若是函数式抽象方法无参数列表,调用无参数构造,若是有两个参数,调用两个参数的构造方法

   @Test
    public  void  test09(){
        //Lambda表达式
        Supplier<Employee> sup=()->new Employee();
        System.out.println(sup.get());
        //ClassName::new
        Supplier<Employee> sup2= Employee::new;
        System.out.println(sup2.get());

    }

7、数组引用

Type[]::new

 @Test
    public  void  test10(){
        //Lambda表达式
        Function<Integer,String[]> fun=(x)->new String[x];
        String[] apply = fun.apply(10);
        System.out.println(apply.length);
        //ClassName::new
        Function<Integer,String[]> fun1= String[]::new;
        String[] apply1 = fun1.apply(10);
        System.out.println(apply1.length);

    }

8、Stream

集合讲的数据,流讲的是计算

①Stream 自己不会存储元素。

②Stream 不会改变源对象。相反,他们会返回一个持有结果的新Stream。

③Stream 操作是延迟执行的。这意味着他们会等到需要结果的时候才执行。

8.1 创建Stream

1、可以通过Collection系列集合提供的stream()或parallelStream()

List<String> list=new ArrayList<>();
Stream<String> stream = list.stream();

2、可以通过Arrays中的静态方法stream()获取数组流

Employee[] employees=new Employee[10];
Stream<Employee> stream1 = Arrays.stream(employees);

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

  • public static IntStream stream(int[ ] array)
  • public static LongStream stream(long[ ] array)
  • public static DoubleStream stream(double[ ] array)

3、通过Stream类中的静态方法of()**

Stream<String> aa = Stream.of("aa", "bb", "cc");

4、创建无限流

迭代的方式生成无限流

 Stream<Integer> iterate = Stream.iterate(0, x -> x + 4);

看效果

iterate.limit(10).forEach(System.out::println);

生成的方法生成无限流

Stream.generate(()->Math.random())
    .limit(10)
    .forEach(System.out::println);

8.2 中间操作

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

筛选与切片

filter-接收Lambda,从流中排出某些元素

List<Employee> employees= Arrays.asList(
      new Employee("张三",18,2000),
      new Employee("李四",25,6000), 
      new Employee("王货",26,8000),
      new Employee("赵六",19,5000),
      new Employee("赵七",89,15000),
      new Employee("赵八",50,150000)
    );
//内部迭代,迭代操作由Stream Api完成
Stream<Employee> employeeStream = employees.stream()
                .filter((e) -> e.getAge() > 30);
//必须有终止操作。所有的方法才会执行
employeeStream.forEach(System.out::println);
 //外部迭代
    @Test
    public void test2(){
        Iterator<Employee> iterator = employees.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }

    }

limit(n)-截断流,使其元素不超过给的数量

 @Test
    public void test3(){ 
        employees.stream()
            //一旦找到满足条件的两数据,就不会再进行查找,发生短路,提高查询效率
                .filter((e) -> e.getSalary() > 6000)
            	.limit(2)
                .forEach(System.out::println);
    }

skip(n)-跳过元素,返回一个扔掉了前n个元素的流,若流中元素不足n个,则返回一个空流,与Limit(n)互补

@Test
    public void test4(){
        employees.stream()
                .filter((e) -> e.getSalary() > 2000)
                .skip(2)
                .forEach(System.out::println);
    }

distinct-筛选,通过流所生成元素的hashCode()he Equals()去除重复元素,需要重写这两个方法

 @Test
    public void test5(){
        employees.stream()
                .filter((e) -> e.getSalary() > 2000)
                .skip(2)
                .distinct()
                .forEach(System.out::println);
    }

映射

map-接收Lambda,将元素转换成其他形式或提取信息。接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素

   @Test
    public void test6(){
        List<String> list=Arrays.asList("aaa","bbb","ccc","ddd","eee");
        list.stream()
                .map((str)->str.toUpperCase())
                .forEach(System.out::println);

        employees.stream().map(Employee::getName)
                .forEach(System.out::println);
    }

flatMap-接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连成一个流

@Test
    public void test7(){
        //使用map
        List<String> list=Arrays.asList("aaa","bbb","ccc","ddd","eee");
        Stream<Stream<Character>> streamStream = list.stream()
                .map(StreamDemo2::filterCharacter);
        streamStream.forEach((s)->{
            s.forEach(System.out::println);
        });
        System.out.println("--------------------------------------");
        //使用flatMap
        list.stream()
                .flatMap(StreamDemo2::filterCharacter)
                .forEach(System.out::println);
    }

    public static Stream<Character> filterCharacter(String str){
        List<Character> list=new ArrayList<>();
        for (Character character:str.toCharArray()){
            list.add(character);
        }
        return list.stream();
    }

区别就像list的add()和andAll()的区别

方法 描述
map(Function f) 接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。
mapToDouble(ToDoubleFunction f) 接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的 DoubleStream。
mapToInt(ToIntFunction f) 接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的 LongStream。
mapToLong(ToLongFunction f) 接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的 LongStream。
flatMap(Function f) 接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流

排序

sorted()-自然排序(Comparable)

sorted(Comparator com)-定制排序(Comparator)

 @Test
 public void test8(){
        List<String> list=Arrays.asList("aaa","bbb","fff","zzz","xxx","ccc","ddd","eee");
        list.stream()
                .sorted()
                .forEach(System.out::println);

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

        employees.stream()
                .sorted((e1,e2)->{
                   if (e1.getAge().equals(e2.getAge())){
                       return e1.getName().compareTo(e2.getName());
                   }else {
                       return e1.getAge().compareTo(e2.getAge());
                   }
                }).forEach(System.out::println);

    }

8.3 终止操作

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

查找与匹配

  List<Employee> employees= Arrays.asList(
            new Employee("张三",18,2000, Employee.Status.FREE),
            new Employee("李四",25,6000, Employee.Status.BUSY),
            new Employee("王货",26,8000, Employee.Status.VOCATION),
            new Employee("赵六",19,5000, Employee.Status.BUSY),
            new Employee("赵七",89,15000, Employee.Status.VOCATION),
            new Employee("赵七",89,15000, Employee.Status.VOCATION),
            new Employee("赵七",89,15000, Employee.Status.BUSY),
            new Employee("赵七",89,15000, Employee.Status.FREE),
            new Employee("赵八",50,150000, Employee.Status.FREE)
    );

allMatch(Predicate p) 检查是否匹配所有元素

 boolean allMatch = employees.stream()
                .allMatch((e) -> e.getStatus().equals(Employee.Status.FREE));
        System.out.println(allMatch);

anyMatch(Predicate p) 检查是否至少匹配一个

boolean anyMatch = employees.stream()
                .anyMatch((e) -> e.getStatus().equals(Employee.Status.BUSY));
        System.out.println(anyMatch);

noneMatch(Predicate p) 检查是否没有匹配所有

boolean noneMatch = employees.stream()
                .noneMatch((e) -> e.getStatus().equals(Employee.Status.BUSY));
        System.out.println(noneMatch);

findFirst()返回第一个元素

Optional<Employee> first = employees.stream()
                .sorted((e1, e2) -> -Double.compare(e1.getSalary(), e2.getSalary()))
                .findFirst();
        System.out.println(first.get());

findAny()返回当前流中的任意

Optional<Employee> any = employees.stream()
                .filter((e) -> e.getStatus().equals(Employee.Status.FREE))
                .findAny();
        System.out.println(any.get());

count() 返回流中元素总数

 long count = employees.stream()
                .count();
        System.out.println(count);

max(Comparator c) 返回流中最大值

Optional<Employee> max = employees.stream()
                .max((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()));
        System.out.println(max);

min(Comparator c) 返回流中最小值

 Optional<Double> min = employees.stream()
                .map(Employee::getSalary)
                .min(Double::compareTo);
        System.out.println(min.get());

forEach(Consumer c) 内部迭代(使用 Collection 接口需要用户去做迭代,称为外部迭代。相反,Stream API 使用内部迭代——它帮你把迭代做了)

归约

reduce(T iden, BinaryOperator b) 可以将流中元素反复结合起来,得到一个值。返回 T

reduce(BinaryOperator b) 可以将流中元素反复结合起来,得到一个值。返回 Optional<T>

 @Test
    public void test2(){
        List<Integer> list=Arrays.asList(1,2,3,4,5,6,7,8,9,10);
        Integer reduce = list.stream()
            //给定一个起始值
                .reduce(0, (x, y) -> x + y);
        System.out.println(reduce);

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

        Optional<Double> optional = employees.stream()
                .map(Employee::getSalary)
                .reduce(Double::sum);
        System.out.println(optional.get());

    }

收集

collect(Collector c) 将流转换为其他形式。接收一个 Collector接口的实现,用于给Stream中元素做汇总的方法

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

 @Test
    public void test3(){
        //toList
        employees.stream()
                .map(Employee::getName)
                .collect(Collectors.toList())
                .forEach(System.out::println);
       System.out.println("============================================");
        //toSet
        employees.stream()
                .map(Employee::getName)
                .collect(Collectors.toSet())
                .forEach(System.out::println);
       System.out.println("============================================");
        //一些自定义的集合
        employees.stream()
                .map(Employee::getName)
                .collect(Collectors.toCollection(HashSet::new))
                .forEach(System.out::println);

    }
 @Test
    public void test4(){
        //总数
        Long count = employees.stream()
                .collect(Collectors.counting());
        System.out.println(count);
       System.out.println("============================================");
        //平均值
        Double collect = employees.stream()           .collect(Collectors.averagingDouble(Employee::getSalary));
        System.out.println(collect);
       System.out.println("============================================");
        //总和
        Double aDouble = employees.stream()
                .collect(Collectors.summingDouble(Employee::getSalary));
        System.out.println(aDouble);
       System.out.println("============================================");
        //最大值
        Optional<Employee> collect1 = employees.stream()
                .collect(Collectors.maxBy((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())));
        System.out.println(collect1.get());
       System.out.println("============================================");
        //最小值
        Optional<Double> collect2 = employees.stream()
                .map(Employee::getSalary)
                .collect(Collectors.minBy(Double::compare));
        System.out.println(collect2.get());
       System.out.println("============================================");
        
    }
/**
     * 分组
     */
    @Test
    public void test5(){
        Map<Employee.Status, List<Employee>> collect = employees.stream()
                .collect(Collectors.groupingBy(Employee::getStatus));
        System.out.println(collect);
        System.out.println("============================================");

    }

    /**
     * 多级分组
     */
    @Test
    public void test6(){
        Map<Employee.Status, Map<String, List<Employee>>> collect = employees.stream()
                .collect(Collectors.groupingBy(Employee::getStatus, Collectors.groupingBy((Employee e) -> {
                    if (e.getAge() <= 35) {
                        return "中年";
                    } else if (e.getAge() <= 50) {
                        return "青年";
                    } else {
                        return "老年";
                    }
                })));
        System.out.println(collect);
    }
    /**
     * 分区
     */
    @Test
    public void test7(){
        Map<Boolean, List<Employee>> collect = employees.stream()
                .collect(Collectors.partitioningBy((e) -> e.getSalary() > 8000));
        System.out.println(collect);
    }

    /**
     * 函数,可以得到总和,平均值等
     */
    @Test
    public void test8(){
        DoubleSummaryStatistics collect = employees.stream()
                .collect(Collectors.summarizingDouble(Employee::getSalary));
        System.out.println(collect.getMax());
        System.out.println(collect.getAverage());
        System.out.println(collect.getCount());
    }
  /**
     *将结果进行连接,可以指定连接直接的符号,第二个,第三个参数可以指定首尾结束的字符串
     */
    @Test
    public  void test9(){
        String collect = employees.stream()
                .map(Employee::getName)
                .collect(Collectors.joining(","));
        System.out.println(collect);
    }

8.4 并行流与串行流

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

/**
 * 并行流
 */
@Test
public void test10(){
    Instant start=Instant.now();

    LongStream.rangeClosed(0,100000000000L)
            .parallel()
            .reduce(0,Long::sum);
    Instant end=Instant.now();
    System.out.println(Duration.between(start,end));
}

9、Optional类

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

9.1 常用方法

Optional.of(T t) : 创建一个 Optional 实例

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

Optional.empty() : 创建一个空的 Optional 实例

@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());
	}

Optional.ofNullable(T t):若 t 不为 null,创建 Optional 实例,否则创建空实例

isPresent() : 判断是否包含值

orElse(T t) : 如果调用对象包含值,返回该值,否则返回t

orElseGet(Supplier s) :如果调用对象包含值,返回该值,否则返回 s 获取的值

@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);
	}

map(Function f): 如果有值对其处理,并返回处理后的Optional,否则返Optional.empty()

flatMap(Function mapper):与 map 类似,要求返回值必须是Optional

@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());
	}

9.2 使用

import java.util.Optional;

//注意:Optional 不能被序列化
public class NewMan {

	private Optional<Godness> godness = Optional.empty();
	
	private Godness god;
	
	public Optional<Godness> getGod(){
		return Optional.of(god);
	}

	public NewMan() {
	}

	public NewMan(Optional<Godness> godness) {
		this.godness = godness;
	}

	public Optional<Godness> getGodness() {
		return godness;
	}

	public void setGodness(Optional<Godness> godness) {
		this.godness = godness;
	}

	@Override
	public String toString() {
		return "NewMan [godness=" + godness + "]";
	}

}
public class Godness {

	private String name;

	public Godness() {
	}

	public Godness(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

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

	@Override
	public String toString() {
		return "Godness [name=" + name + "]";
	}
//运用 Optional 的实体类
	@Test
	public void test6(){
		Optional<Godness> godness = Optional.ofNullable(new Godness("林志玲"));
		
		Optional<NewMan> op = Optional.ofNullable(new NewMan(godness));
		String name = getGodnessName2(op);
		System.out.println(name);
	}
	
	public String getGodnessName2(Optional<NewMan> man){
		return man.orElse(new NewMan())
				  .getGodness()
				  .orElse(new Godness("苍老师"))
				  .getName();
	}

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

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

public interface MyInterface {
    void query(String name);
    default String getName(){
        return "如意";
    }
}

10.1 接口中的默认方法

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

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

选择父类中的方法。如果一个父类提供了具体的实现,那么接口中具有相同名称和参数的默认方法会被忽略。

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

10.2 接口中的静态

public interface MyInterface {
    void query(String name);
    default String getName(){
        return "如意";
    }
    static void show(){
        System.out.println("hello Lambda");
    }
}

11、时间和日期API

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

方法 描述 使用
now() 静态方法,根据当前时间创建对象 LocalDate localDate= LocalDate.now();
LocalTime localTime = LocalTime.now();
LocalDateTime localDateTime =LocalDateTime.now();
of() 静态方法,根据指定日期/时间创建对象 LocalDate localDate = LocalDate.of(2016, 10, 26);
LocalTime localTime = LocalTime.of(02, 22, 56);
LocalDateTime localDateTime = LocalDateTime.of(2016, 10, 26, 12, 10, 55);
plusDays,
plusWeeks,
plusMonths,
plusYears
向当前 LocalDate 对象添加几天、几周、几个月、几年
minusDays,
minusWeeks,
minusMonths,
minusYears
从当前 LocalDate 对象减去几天、几周、几个月、几年
plus, minus 添加或减少一个 Duration 或 Period
withDayOfMonth,
withDayOfYear,
withMonth,
withYear
将月份天数、年份天数、月份、年份 修 改 为 指 定 的 值 并 返 回 新 的LocalDate 对象
getDayOfMonth 获得月份天数(1-31)
getDayOfYear 获得年份天数(1-366)
getDayOfWeek 获得星期几(返回一个DayOfWeek枚举值)
getMonth 获得月份, 返回一个 Month 枚举值
getMonthValue 获得月份(1-12)
getYear 获得年份
until 获得两个日期之间的 Period 对象,或者指定 ChronoUnits 的数字
isBefore, isAfter 比较两个 LocalDate
isLeapYear 判断是否是闰年
//1. LocalDate、LocalTime、LocalDateTime
	@Test
	public void test1(){
		LocalDateTime ldt = LocalDateTime.now();
		System.out.println(ldt);
		
		LocalDateTime ld2 = LocalDateTime.of(2016, 11, 21, 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());
	}

11.1 Instant 时间戳

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

//2. Instant : 时间戳。 (使用 Unix 元年  1970年1月1日 00:00:00 所经历的毫秒值)
	@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);
	}

11.2 Duration 和 Period

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());
	}

11.3 日期的操纵

TemporalAdjuster : 时间校正器。有时我们可能需要获取例如:将日期调整到“下个周日”等操作。

TemporalAdjusters : 该类通过静态方法提供了大量的常用 TemporalAdjuster 的实现

//4. TemporalAdjuster : 时间校正器
	@Test
	public void test4(){
	LocalDateTime ldt = LocalDateTime.now();
		System.out.println(ldt);
		
		LocalDateTime ldt2 = ldt.withDayOfMonth(10);
		System.out.println(ldt2);
		
		LocalDateTime ldt3 = ldt.with(TemporalAdjusters.next(DayOfWeek.SUNDAY));
		System.out.println(ldt3);
		
		//自定义:下一个工作日
		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);
		
	}

11.4 解析与格式化

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

  • 预定义的标准格式
  • 语言环境相关的格式
  • 自定义的格式
//5. DateTimeFormatter : 解析和格式化日期或时间
	@Test
	public void test5(){
//		DateTimeFormatter dtf = DateTimeFormatter.ISO_LOCAL_DATE;
		
		DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss E");
		
		LocalDateTime ldt = LocalDateTime.now();
		String strDate = ldt.format(dtf);
		
		System.out.println(strDate);
		
		LocalDateTime newLdt = ldt.parse(strDate, dtf);
		System.out.println(newLdt);
	}

11.5 时区的处理

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

ZonedDate、ZonedTime、ZonedDateTime

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

//6.ZonedDate、ZonedTime、ZonedDateTime : 带时区的时间或日期
	@Test
	public void test7(){
		LocalDateTime ldt = LocalDateTime.now(ZoneId.of("Asia/Shanghai"));
		System.out.println(ldt);
		
		ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("US/Pacific"));
		System.out.println(zdt);
	}
	
	@Test
	public void test6(){
		Set<String> set = ZoneId.getAvailableZoneIds();
		set.forEach(System.out::println);
	}

猜你喜欢

转载自blog.csdn.net/qq_39744066/article/details/83578545