文章目录

  • Lambda 表达式
    • Lambda 表达式的基础语法
    • 方法引用
    • Lambda 表达式需要“函数式接口”的支持
      • Java8 内置的四大核心函数式接口
  • Stream API
    • Stream API 的操作步骤
    • 筛选与切片
    • Stream 映射Map与flatMap
    • Stream 排序
    • Stream 终止操作
      • 查找与匹配
    • Stream 归约与收集
  • Optional 容器类
  • 并行流与串行流
    • ForkJoin框架
  • Date Time时间 API
    • LocalDate、LocalTime、LocalDateTime
    • Instant 时间戳、Duration、Period
    • TemporalAdjuster : 时间校正器
    • DateTimeFormatter : 解析和格式化日期或时间
    • ZonedDate、ZonedTime、ZonedDateTime:带时区的时间或日期
    • 甜点:阿里巴巴java开发手册泰山版对日期时间的处理要求
    • Date Time API代码示例
  • Java8 Base64
  • 参考网址

Lambda 表达式

Lambda 表达式的基础语法

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

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

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

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

实现类

package com.atguigu.java8;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import org.junit.Test;public class TestLambda2 {@Testpublic void test1(){int num = 0;//jdk 1.7 前,必须是 finalRunnable r = new Runnable() {@Overridepublic void run() {System.out.println("Hello World!" + num);}};r.run();System.out.println("-------------------------------");Runnable r1 = () -> System.out.println("Hello Lambda!");r1.run();}@Testpublic void test2(){Consumer<String> con = x -> System.out.println(x);con.accept("我大尚硅谷威武!");}@Testpublic void test3(){Comparator<Integer> com = (x, y) -> {System.out.println("函数式接口");return Integer.compare(x, y);};}@Testpublic void test4(){Comparator<Integer> com = (x, y) -> Integer.compare(x, y);}@Testpublic void test5(){//      String[] strs;
//      strs = {"aaa", "bbb", "ccc"};List<String> list = new ArrayList<>();show(new HashMap<>());}public void show(Map<String, Integer> map){}//需求:对一个数进行运算@Testpublic void test6(){Integer num = operation(100, (x) -> x * x);System.out.println(num);System.out.println(operation(200, (y) -> y + 200));}public Integer operation(Integer num, MyFun mf){return mf.getValue(num);}
}

接口类

package com.atguigu.java8;@FunctionalInterface
public interface MyPredicate<T> {public boolean test(T t);
}

方法引用

  • 方法引用:若 Lambda 体中的功能,已经有方法提供了实现,可以使用方法引用
    (可以将方法引用理解为 Lambda 表达式的另外一种表现形式)

    • 对象的引用 :: 实例方法名
    • 类名 :: 静态方法名
    • 类名 :: 实例方法名
      • 注意:
        ①方法引用所引用的方法的参数列表与返回值类型,需要与函数式接口中抽象方法的参数列表和返回值类型保持一致!
        ②若Lambda 的参数列表的第一个参数,是实例方法的调用者,第二个参数(或无参)是实例方法的参数时,格式: ClassName::MethodName
  • 构造器引用 :构造器的参数列表,需要与函数式接口中参数列表保持一致!
    • 类名 :: new
  • 数组引用
    • 类型[] :: new;
package com.atguigu.java8;import java.io.PrintStream;
import java.util.Comparator;
import java.util.function.BiFunction;
import java.util.function.BiPredicate;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import org.junit.Test;public class TestMethodRef {//数组引用@Testpublic 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);}//构造器引用@Testpublic void test7(){Function<String, Employee> fun = Employee::new;BiFunction<String, Integer, Employee> fun2 = Employee::new;}@Testpublic 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());}//类名 :: 实例方法名@Testpublic 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()));}//类名 :: 静态方法名@Testpublic void test4(){Comparator<Integer> com = (x, y) -> Integer.compare(x, y);System.out.println("-------------------------------------");Comparator<Integer> com2 = Integer::compare;}@Testpublic 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));}//对象的引用 :: 实例方法名@Testpublic 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());}@Testpublic 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;}}

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

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

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

  • Consumer : 消费型接口
    void accept(T t);
  • Supplier : 供给型接口
    T get();
  • Function<T, R> : 函数型接口
    R apply(T t);
  • Predicate : 断言型接口
    boolean test(T t);

示例代码

public class TestLambda3 {//Predicate<T> 断言型接口:@Testpublic 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;}//Function<T, R> 函数型接口:@Testpublic 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);}//Supplier<T> 供给型接口 :@Testpublic 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;}//Consumer<T> 消费型接口 :@Testpublic void test1(){happy(10000, (m) -> System.out.println("你们刚哥喜欢大宝剑,每次消费:" + m + "元"));} public void happy(double money, Consumer<Double> con){con.accept(money);}
}

Stream API

Stream API 的操作步骤

  1. 创建 Stream
  2. 中间操作:不会做任何的处理
  3. 终止操作(终端操作):只有当做终止操作时,所有的中间操作会一次性的全部执行,称为“惰性求值”

筛选与切片

filter——接收 Lambda , 从流中排除某些元素。
limit——截断流,使其元素不超过给定数量。
skip(n) —— 跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一个空流。与 limit(n) 互补
distinct——筛选,通过流所生成元素的 hashCode() 和 equals() 去除重复元素

package com.atguigu.java8;import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Stream;import org.junit.Test;/** 一、Stream API 的操作步骤:* * 1. 创建 Stream* * 2. 中间操作* * 3. 终止操作(终端操作)*/
public class TestStreamaAPI {//1. 创建 Stream@Testpublic 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. 中间操作List<Employee> emps = Arrays.asList(new Employee(102, "李四", 59, 6666.66),new Employee(101, "张三", 18, 9999.99),new Employee(103, "王五", 28, 3333.33),new Employee(104, "赵六", 8, 7777.77),new Employee(104, "赵六", 8, 7777.77),new Employee(104, "赵六", 8, 7777.77),new Employee(105, "田七", 38, 5555.55));/*筛选与切片filter——接收 Lambda , 从流中排除某些元素。limit——截断流,使其元素不超过给定数量。skip(n) —— 跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一个空流。与 limit(n) 互补distinct——筛选,通过流所生成元素的 hashCode() 和 equals() 去除重复元素*///内部迭代:迭代操作 Stream API 内部完成@Testpublic void test2(){//所有的中间操作不会做任何的处理Stream<Employee> stream = emps.stream().filter((e) -> {System.out.println("测试中间操作");return e.getAge() <= 35;});//只有当做终止操作时,所有的中间操作会一次性的全部执行,称为“惰性求值”stream.forEach(System.out::println);}//外部迭代@Testpublic void test3(){Iterator<Employee> it = emps.iterator();while(it.hasNext()){System.out.println(it.next());}}@Testpublic void test4(){emps.stream().filter((e) -> {System.out.println("短路!"); // &&  ||return e.getSalary() >= 5000;}).limit(3).forEach(System.out::println);}@Testpublic void test5(){emps.parallelStream().filter((e) -> e.getSalary() >= 5000).skip(2).forEach(System.out::println);}@Testpublic void test6(){emps.stream().distinct().forEach(System.out::println);}
}

Stream 映射Map与flatMap

  • map:接收 Lambda,将元素转换成其他形式或提取信息。接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。【Stream<Stream> stream2】
  • flatMap:接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流。【Stream stream3】
package com.atguigu.java8;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
import org.junit.Test;//1. 创建 Stream
public class TestStreamAPI1 {List<Employee> emps = Arrays.asList(new Employee(102, "李四", 59, 6666.66),new Employee(101, "张三", 18, 9999.99),new Employee(103, "王五", 28, 3333.33),new Employee(104, "赵六", 8, 7777.77),new Employee(104, "赵六", 8, 7777.77),new Employee(104, "赵六", 8, 7777.77),new Employee(105, "田七", 38, 5555.55));//2. 中间操作/*映射map——接收 Lambda , 将元素转换成其他形式或提取信息。接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。【Stream<Stream<Character>> stream2】flatMap——接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流【Stream<Character> stream3】*/@Testpublic 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();}/*sorted()——自然排序sorted(Comparator com)——定制排序*/@Testpublic 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);}
}

Stream 排序

  • sorted()——自然排序Comparable
  • sorted(Comparator com)——定制排序Comparator
package com.atguigu.java8;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
import org.junit.Test;//1. 创建 Stream
public class TestStreamAPI1 {List<Employee> emps = Arrays.asList(new Employee(102, "李四", 59, 6666.66),new Employee(101, "张三", 18, 9999.99),new Employee(103, "王五", 28, 3333.33),new Employee(104, "赵六", 8, 7777.77),new Employee(104, "赵六", 8, 7777.77),new Employee(104, "赵六", 8, 7777.77),new Employee(105, "田七", 38, 5555.55));/*sorted()——自然排序sorted(Comparator com)——定制排序*/@Testpublic 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);}
}

Stream 终止操作

查找与匹配

  • allMatch——检查是否匹配所有元素
  • anyMatch——检查是否至少匹配一个元素
  • noneMatch——检查是否没有匹配的元素
  • findFirst——返回第一个元素
  • findAny——返回当前流中的任意元素
  • count——返回流中元素的总个数
  • max——返回流中最大值
  • min——返回流中最小值
package com.atguigu.java8;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;
import org.junit.Test;
import com.atguigu.java8.Employee.Status;public class TestStreamAPI2 {List<Employee> emps = Arrays.asList(new Employee(102, "李四", 59, 6666.66, Status.BUSY),new Employee(101, "张三", 18, 9999.99, Status.FREE),new Employee(103, "王五", 28, 3333.33, Status.VOCATION),new Employee(104, "赵六", 8, 7777.77, Status.BUSY),new Employee(104, "赵六", 8, 7777.77, Status.FREE),new Employee(104, "赵六", 8, 7777.77, Status.FREE),new Employee(105, "田七", 38, 5555.55, Status.BUSY));// 终止操作@Testpublic void test1(){// allMatch——检查是否匹配所有元素boolean bl = emps.stream().allMatch((e) -> e.getStatus().equals(Status.BUSY));System.out.println(bl);// anyMatch——检查是否至少匹配一个元素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);}@Testpublic 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("--------------------------------");//parallelStream多个线程并行获取Optional<Employee> op2 = emps.parallelStream().filter((e) -> e.getStatus().equals(Status.FREE)).findAny();System.out.println(op2.get());}@Testpublic 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());}//注意:流进行了终止操作后,不能再次使用@Testpublic 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);}
}

Stream 归约与收集

  • 归约:reduce(T identity, BinaryOperator) / reduce(BinaryOperator) ——可以将流中元素反复结合起来,得到一个值。
    map-reduce模式应用广泛,如Google进行网络搜索的大数据应用
  • collect:将流转换为其他形式。接收一个 Collector接口的实现,用于给Stream中元素做汇总的方法
    特殊功能点:分组、多级分组、分区
package com.atguigu.java8;
import java.util.Arrays;
import java.util.DoubleSummaryStatistics;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import org.junit.Test;
import com.atguigu.java8.Employee.Status;public class TestStreamAPI3 {List<Employee> emps = Arrays.asList(new Employee(102, "李四", 79, 6666.66, Status.BUSY),new Employee(101, "张三", 18, 9999.99, Status.FREE),new Employee(103, "王五", 28, 3333.33, Status.VOCATION),new Employee(104, "赵六", 8, 7777.77, Status.BUSY),new Employee(104, "赵六", 8, 7777.77, Status.FREE),new Employee(104, "赵六", 8, 7777.77, Status.FREE),new Employee(105, "田七", 38, 5555.55, Status.BUSY));//3. 终止操作/*归约reduce(T identity, BinaryOperator) / reduce(BinaryOperator) ——可以将流中元素反复结合起来,得到一个值。*/@Testpublic 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());}//需求:搜索名字中 “六” 出现的次数@Testpublic 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());}//collect——将流转换为其他形式。接收一个 Collector接口的实现,用于给Stream中元素做汇总的方法@Testpublic 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);}@Testpublic 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());}//分组@Testpublic void test5(){Map<Status, List<Employee>> map = emps.stream().collect(Collectors.groupingBy(Employee::getStatus));System.out.println(map);}//多级分组@Testpublic 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 "中年";elsereturn "成年";})));System.out.println(map);}//分区@Testpublic void test7(){Map<Boolean, List<Employee>> map = emps.stream().collect(Collectors.partitioningBy((e) -> e.getSalary() >= 5000));System.out.println(map);}//@Testpublic void test8(){String str = emps.stream().map(Employee::getName).collect(Collectors.joining("," , "----", "----"));System.out.println(str);}@Testpublic void test9(){Optional<Double> sum = emps.stream().map(Employee::getSalary).collect(Collectors.reducing(Double::sum));System.out.println(sum.get());}
}

Optional 容器类

Optional 容器类:用于尽量避免空指针异常

  • 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 类似,要求返回值必须是Optional

最常用的写法
ofNullable-可以是null,可以不是,所以使用前需要先isPresent()判断一下。 实际上ofNullable()是of(value) 与empty()的结合体

// ofNullable-可以是null,可以不是,所以使用前需要先isPresent()判断一下。 实际上ofNullable()是of(value) 与empty()的结合体
Optional<Employee> op = Optional.ofNullable(new Employee());
if(op.isPresent()){System.out.println(op.get());
}

示例代码

package com.atguigu.java8;
import java.util.Optional;
import org.junit.Test;public class TestOptional {@Testpublic 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());}@Testpublic 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);}@Testpublic void test2(){/*Optional<Employee> op = Optional.ofNullable(null);System.out.println(op.get());*///       Optional<Employee> op = Optional.empty();
//      System.out.println(op.get());}@Testpublic void test1(){Optional<Employee> op = Optional.of(new Employee());Employee emp = op.get();System.out.println(emp);}@Testpublic void test5(){Man man = new Man();String name = getGodnessName(man);System.out.println(name);}//需求:获取一个男人心中女神的名字public String getGodnessName(Man man){if(man != null){Godness g = man.getGod();if(g != null){return g.getName();}}return "苍老师";}//运用 Optional 的实体类@Testpublic 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();}
}

Godness实体类

package com.atguigu.java8;
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;}@Overridepublic String toString() {return "Godness [name=" + name + "]";}
}

man实体类

package com.atguigu.java8;
public class Man {private Godness god;public Man() {}public Man(Godness god) {this.god = god;}public Godness getGod() {return god;}public void setGod(Godness god) {this.god = god;}@Overridepublic String toString() {return "Man [god=" + god + "]";}
}

并行流与串行流

java8 并行流 parallel()底层是Fork/Join 框架,其CPU利用率极高!

ForkJoin框架

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

调用类

package com.atguigu.java8;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;
import org.junit.Test;public class TestForkJoin {@Testpublic void test1(){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)); //112-1953-1988-2654-2647-20663-113808}@Testpublic void test2(){long start = System.currentTimeMillis();long sum = 0L;//普通for循环方式对比for (long i = 0L; i <= 10000000000L; i++) {sum += i;}System.out.println(sum);long end = System.currentTimeMillis();System.out.println("耗费的时间为: " + (end - start)); //34-3174-3132-4227-4223-31583}@Testpublic void test3(){long start = System.currentTimeMillis();// java8 并行流 parallel()Long sum = LongStream.rangeClosed(0L, 10000000000L).parallel().sum();System.out.println(sum);long end = System.currentTimeMillis();System.out.println("耗费的时间为: " + (end - start)); //2061-2053-2086-18926}}

实现类

package com.atguigu.java8;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;}@Overrideprotected 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();}}}

Date Time时间 API

LocalDate、LocalTime、LocalDateTime

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

注:ISO-8601日历系统是国际标准化组织制定的现代公民的日期和时间的表示法

package com.atguigu.java8;
import java.time.DayOfWeek;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.Period;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.Set;
import org.junit.Test;
public class TestLocalDateTime {//6.ZonedDate、ZonedTime、ZonedDateTime : 带时区的时间或日期@Testpublic 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);}@Testpublic void test6(){Set<String> set = ZoneId.getAvailableZoneIds();set.forEach(System.out::println);}//5. DateTimeFormatter : 解析和格式化日期或时间@Testpublic 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);}//4. TemporalAdjuster : 时间校正器@Testpublic 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);}//3.//Duration : 用于计算两个“时间”间隔//Period : 用于计算两个“日期”间隔@Testpublic 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());}//2. Instant : 时间戳。 (使用 Unix 元年  1970年1月1日 00:00:00 所经历的毫秒值)@Testpublic 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);}//1. LocalDate、LocalTime、LocalDateTime@Testpublic 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());}
}

Instant 时间戳、Duration、Period

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

TemporalAdjuster : 时间校正器

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

DateTimeFormatter : 解析和格式化日期或时间

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

  • 预定义的标准格式 : DateTimeFormatter.ISO**
  • 自定义的格式:DateTimeFormatter.ofPattern(格式)
  • 语言环境相关的格式 : test5()示例代码的最后一个实现

ZonedDate、ZonedTime、ZonedDateTime:带时区的时间或日期

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

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

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

获取所有时区信息

Set<String> set = ZoneId.getAvailableZoneIds();
set.forEach(System.out::println);

指定一个时区获取时间

LocalDateTime ldt = LocalDateTime.now(ZoneId.of("Asia/Shanghai"));

甜点:阿里巴巴java开发手册泰山版对日期时间的处理要求

阿里巴巴2020.04.22发布的 java开发手册泰山版-下载 中对日期也做了特殊要求:详细内容大家可点击上方下载查看手册(五) 日期时间章节,关于闰年闰月部分特殊,我已摘出来如下:

  • 【强制】不要在程序中写死一年为 365 天,避免在公历闰年时出现日期转换错误或程序逻辑 错误。
    正例:
// 获取今年的天数
int daysOfThisYear = LocalDate.now().lengthOfYear(); // 获取指定某年的天数
LocalDate.of(2011, 1, 1).lengthOfYear();

反例: // 第一种情况:在闰年 366 天时,出现数组越界异常

int[] dayArray = new int[365];
// 第二种情况:一年有效期的会员制,今年 1 月 26 日注册,硬编码 365 返回的却是 1 月 25 日
Calendar calendar = Calendar.getInstance(); calendar.set(2020, 1, 26);
calendar.add(Calendar.DATE, 365);
  • 【推荐】避免公历闰年 2 月问题。闰年的 2 月份有 29 天,一年后的那一天不可能是 2 月 29 日。

Date Time API代码示例

package com.atguigu.java8;
import java.time.DayOfWeek;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.Period;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.Set;
import org.junit.Test;
public class TestLocalDateTime {//6.ZonedDate、ZonedTime、ZonedDateTime : 带时区的时间或日期@Testpublic 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);}@Testpublic void test6(){Set<String> set = ZoneId.getAvailableZoneIds();set.forEach(System.out::println);}//5. DateTimeFormatter : 解析和格式化日期或时间@Testpublic 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);}//4. TemporalAdjuster : 时间校正器@Testpublic 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);}//3.//Duration : 用于计算两个“时间”间隔//Period : 用于计算两个“日期”间隔@Testpublic 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());}//2. Instant : 时间戳。 (使用 Unix 元年  1970年1月1日 00:00:00 所经历的毫秒值)@Testpublic 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);}//1. LocalDate、LocalTime、LocalDateTime@Testpublic 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());}
}

Java8 Base64

在Java 8中,Base64编码已经成为Java类库的标准。
Java 8 内置了 Base64 编码的编码器和解码器。
Base64工具类提供了一套静态方法获取下面三种BASE64编解码器:

  • 基本:输出被映射到一组字符A-Za-z0-9+/,编码不添加任何行标,输出的解码仅支持A-Za-z0-9+/。
  • URL:输出映射到一组字符A-Za-z0-9+_,输出是URL和文件。
  • MIME:输出隐射到MIME友好格式。输出每行不超过76字符,并且使用’\r’并跟随’\n’作为分割。编码输出最后没有行分割。

参考网址

菜鸟教程: https://www.runoob.com/java/java8-new-features.html
尚硅谷:http://www.gulixueyuan.com/course/56/tasks
1、Lambda 表达式
2、方法引用
3、函数式接口
4、默认方法
5、Stream
6、Optional 类
7、Nashorn, JavaScript 引擎
8、新的日期时间 API
9、Base64

java8新特性【Lambda、Stream API、Optional、Date Time API 、并行流与串行流】相关推荐

  1. Java8新特性 Lambda、Stream、Optional实现原理

    Java8新特性 Lambda.Stream.Optional实现原理 一.接口中默认方法修饰为普通方法 二.Lambda表达式 2.1.什么是Lambda表达式 2.2.为什么要使用Lambda表达 ...

  2. java8新特性Lambda和Stream以及函数式接口等新特性介绍

    主要内容 1.Lambda 表达式 2.函数式接口 3.方法引用与构造器引用 4.Stream API 5.接口中的默认方法与静态方法 6.新时间日期API 7.其他新特性 Java 8新特性简介 速 ...

  3. 【java8新特性】——Stream API详解(二)

    一.简介 java8新添加了一个特性:流Stream.Stream让开发者能够以一种声明的方式处理数据源(集合.数组等),它专注于对数据源进行各种高效的聚合操作(aggregate operation ...

  4. 使用Java8新特性(stream流、Lambda表达式)实现多个List 的笛卡尔乘积 返回需要的List<JavaBean>

    需求分析: 有两个Long类型的集合 : List<Long> tagsIds; List<Long> attributesIds; 现在需要将这两个Long类型的集合进行组合 ...

  5. 【小家java】java8新特性之---全新的日期、时间API(JSR 310规范),附SpringMVC、Mybatis中使用JSR310的正确姿势

    [小家java]java5新特性(简述十大新特性) 重要一跃 [小家java]java6新特性(简述十大新特性) 鸡肋升级 [小家java]java7新特性(简述八大新特性) 不温不火 [小家java ...

  6. java8新特性-lambda表达式入门学习

    定义 jdk8发布新特性中,lambda是一大亮点之一.lambda表达式能够简化我们对数据的操作,减少代码量,大大提升我们的开发效率.Lambda 表达式"(lambda expressi ...

  7. java stream byte_乐字节-Java8新特性之Stream流(上)

    上一篇文章,小乐给大家介绍了<Java8新特性之方法引用>,下面接下来小乐将会给大家介绍Java8新特性之Stream,称之为流,本篇文章为上半部分. 1.什么是流? Java Se中对于 ...

  8. Java8新特性----Lambda表达式详细探讨

    Java8新特性 Lambda表达式 入门演示 案例1 如何解决 cannot be cast to java.lang.Comparable问题? 案例2 优化方式一 : 策略设计模式 优化方式二: ...

  9. java8新特性(5)— Optional 类

    java8新特性(5)- Optional 类 空指针解决方案 package com.common.jdk8;import java.util.Optional;//Optional 类是一个可以为 ...

最新文章

  1. java中double类型精度丢失问题及解决方法
  2. Cell:绝对异养型生物改造成完全自养型生物
  3. HDU1029 - Ignatius and the Princess IV【水题】
  4. adb shell am 命令启动activity、Service、Borascast
  5. libstrophe 安装
  6. php gif裁剪,PHP实现图片裁剪与缩放的几种方法
  7. 开发人员如何了解用户和需求
  8. GitHub入门:如何上传与下载工程?
  9. html5 拍照 清晰度,html5强大的功能(一)
  10. nginx post请求超时_Nginx 的超时 timeout 配置详解
  11. 4. HTML DOM Event 对象
  12. java实用技巧论坛_学习Java前要掌握6大技巧!
  13. fiddler 手机 https 抓包
  14. 关于机器人方面的sci论文_机器人领域国际期刊(SCI收录)
  15. 【HDLBits刷题笔记】Exams/ece241 2013 q7
  16. 你有多久没有看过星星
  17. 计算机网络管理工程师证书考试试题,2016年计算机软件水平考试网络工程师练习题...
  18. Linux git环境搭建和常用指令--推送至Github为例
  19. java oop6_Java oop代码6(原创方法):5道用上extends继承,子类,父类的题
  20. 2015.02.28侬自语

热门文章

  1. Python邮件功能 - 使用163邮箱SMTP服务器发送邮件
  2. HC-05蓝牙模块主从机AT指令
  3. Apollo星火计划学习笔记——第七讲自动驾驶规划技术原理2
  4. 2‘13寸墨水屏时钟diy教程
  5. 灵活用工系统开发|灵活用工平台如何可以发展吗?
  6. python爬取QQ音乐评论信息
  7. matlab rof算法,ROF|MATLAB 其它技术应用|MATLAB技术论坛 - Powered by Discuz!
  8. AI与供应链碰撞,会产生怎样的火花?
  9. 架构思想--基础架构
  10. 不可用于python的标识符有_下面哪个不是Python合法的标识符