Java 8使用总结

lambda表达式

Runnable r2 =  () -> System.out.println("hello");
  • 箭头左侧,指定了lambda表达式的参数
  • 箭头右侧,lambda体,即要执行的功能

1.无参无返回值

 Runnable r1 = new Runnable() {
     @Override
     public void run() {
         System.out.println("111111111");
     }
 };
 r1.run();

 System.out.println("---------------");
 Runnable r2 = () -> System.out.println("---");
 r2.run();

2.一个参数,但是没有返回值。

Consumer<String> con = new Consumer<String>() {
    @Override
    public void accept(String s) {
        System.out.println(s);
    }
};
con.accept("谎言和誓言的区别是什么?");
System.out.println("*******************");

Consumer<String> con1 = (String s) -> {
    System.out.println(s);
};
con1.accept("谎言和誓言的区别是什么?");

3.一个参数时()可以省略

Consumer<String> fun2 = a -> System.out.println(a);

4.两个参数并有返回值


BinaryOperator<Integer> bo1 = (x,y) ->{
      System.out.println("实现接口的方法");
      return x + y;
  };
 System.out.println(bo1.apply(10, 20));

5.参数的类型可以省略,类型可由编译器判断

 Consumer<String> con1 = (String s) -> {
      System.out.println(s);
  };
  con1.accept("一个是听得人当真了,一个是说的人当真了");

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

  Consumer<String> con2 = (s) -> {
      System.out.println(s);
  };
  con2.accept("一个是听得人当真了,一个是说的人当真了");

6.当 Lambda 体只有一条语句时,return 与大括号若有,都可以省略

Comparator<Integer> com1 = (o1, o2) -> {
		return o1.compareTo(o2);
 };

 System.out.println(com1.compare(12,6));

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

 Comparator<Integer> com2 = (o1,o2) -> o1.compareTo(o2);

 System.out.println(com2.compare(12,21));

Lambda表达式的本质:作为函数式接口的实例,以前用匿名内部类实现的现在都可以用Lambda表达式来写

函数式接口

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

四大核心函数式接口

  • Consumer 消费型接口
  • Supplier 供给型接口
  • Function<T,R> 函数型接口
  • Predicate 断定型接口
函数式接口参数类型返回值用途
Consumer 消费型接口Tvoid对类型为Tde 对象应用操作,包含方法void accetpt(T t)
Supplier 供给型接口T返回类型为T的对象,包含方法:T get()
Function<T,R> 函数型接口TR对类型为T的对象应用操作,并返回结果。结果是R类型的对象。包含方法:R apply(T t)
Predicate 断定型接口Tboolean确定类型为T的对象是否满足某约束,并返回boolean 值。包含方法:boolean test(T t)

方法引用&构造器引用&数组引用

方法引用

方法引用,本质上就是Lambda表达式,而Lambda表达式作为函数式接口的实例。所以方法引用,也是函数式接口的实例。

1.对象引用非静态方法

Consumer<String> con1 = str -> System.out.println(str);
con1.accept("北京");

PrintStream ps = System.out;
Consumer<String> con2 = ps::println;
con2.accept("beijing");

2.类引用静态方法

Comparator<Integer> com1 = (t1,t2) -> Integer.compare(t1,t2);
System.out.println(com1.compare(12,21));

Comparator<Integer> com2 = Integer::compare;
System.out.println(com2.compare(12,3));

3.类引用非静态方法

Comparator<String> com1 = (s1,s2) -> s1.compareTo(s2);
System.out.println(com1.compare("abc","abd"));

Comparator<String> com2 = String :: compareTo;
System.out.println(com2.compare("abd","abm"));

构造器引用

  • Supplier中的T get()
  Supplier<Employee>  sup1 = () -> new Employee();
  System.out.println(sup1.get());

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

  Supplier<Employee>  sup2 = Employee :: new;
  System.out.println(sup2.get());
  • Function中的R apply(T t)
 Function<Integer,Employee> func1 = id -> new Employee(id);
  Employee employee = func1.apply(1001);
  System.out.println(employee);

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

  Function<Integer,Employee> func2 = Employee :: new;
  Employee employee1 = func2.apply(1002);
  System.out.println(employee1);
  • iFunction中的R apply(T t,U u)
 BiFunction<Integer,String,Employee> func1 = (id, name) -> new Employee(id,name);
 System.out.println(func1.apply(1001,"Tom"));

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

 BiFunction<Integer,String,Employee> func2 = Employee :: new;
 System.out.println(func2.apply(1002,"Tom"));

数组引用

 Function<Integer,String[]> func1 = length -> new String[length];
 String[] arr1 = func1.apply(5);
 System.out.println(Arrays.toString(arr1));

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

 Function<Integer,String[]> func2 = String[] :: new;
 String[] arr2 = func2.apply(10);
 System.out.println(Arrays.toString(arr2));

Stream API

说明

  • Java8中有两大最为重要的改变。第一个是 Lambda 表达式;另外一个则
    是 Stream API。
  • Stream API ( java.util.stream) 把真正的函数式编程风格引入到Java中。这
    是目前为止对Java类库最好的补充,因为Stream API可以极大提供Java程
    序员的生产力,让程序员写出高效率、干净、简洁的代码。
  • Stream API 提供了一种高效且易于使用的处理数据的方式。
  • Stream 和 Collection 集合的区别:Collection 是一种静态的内存数据
    结构,而 Stream 是有关计算的。前者是主要面向内存,存储在内存中,
    后者主要是面向 CPU,通过 CPU 实现计算。

Stream操作的三个步骤

1.创建Stream

一个数据源(如:集合、数组),获取一个流。

2.中间操作

一个中间操作链,对数据源的数据进行处理。

3.终止操作(终端操作)

一旦执行终止操作,就执行中间操作链,并产生结果。之后,流不能再被使用。

创建Stream的四种方式

1.通过集合

List<Employee> employees = EmployeeData.getEmployees();

//default Stream<E> stream() : 返回一个顺序流
Stream<Employee> employeeStream = employees.stream();

//default Stream<E> parallelStream() : 返回一个并行流
Stream<Employee> parallelStream = employees.parallelStream();

2.通过数组

int[] arr = {1, 2, 3, 4, 5, 6};

//调用Arrays类的static <T> Stream<T> stream(T[] array): 返回一个流
IntStream stream = Arrays.stream(arr);

3.通过Stream的of()

 Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6);
 System.out.println(stream);

4.创建无限流

 //迭代
 //public static<T> Stream<T> iterate(final T seed, final UnaryOperator<T> f)
 //遍历10以内的偶数
 Stream.iterate(0,t->t+2).limit(10).forEach(System.out::println);

 //生成
 //public static<T> Stream<T> generate(Supplier<T> s)
 Stream.generate(Math::random).limit(10).forEach(System.out::println);

中间操作

1.筛选与切片

方法描述
filter(Predicate p)接收 Lambda , 从流中排除某些元素
distinct()筛选,通过流所生成元素的 hashCode() 和 equals() 去除重复元素
limit(long maxSize)截断流,使其元素不超过给定数量
skip(long n)跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一个空流。与 limit(n) 互补
    @Test
    public void testFilter(){
        Stream.iterate(0, x -> x + 1).limit(100).filter(x -> x % 2 == 0).forEach(System.out::println);

        //https://blog.csdn.net/weixin_43318134/article/details/104442023
        // 收集到List
        List<Integer> collect = Stream.iterate(0, x -> x + 1).limit(100).filter(x -> x % 2 == 0).collect(Collectors.toList());
        // 收集到set
        Set<Integer> set = Stream.iterate(0, x -> x + 1).limit(100).filter(x -> x % 2 == 0).collect(Collectors.toSet());
        // 收集到指定集合中
        ArrayList<Integer> arrayList = Stream.iterate(0, x -> x + 1).limit(100).filter(x -> x % 2 == 0).collect(Collectors.toCollection(ArrayList::new));
        // 收集到Object数组
        Object[] objects = Stream.iterate(0, x -> x + 1).limit(100).filter(x -> x % 2 == 0).toArray();
        // 收集到指定数组
        Integer[] integers = Stream.iterate(0, x -> x + 1).limit(100).filter(x -> x % 2 == 0).toArray(Integer[]::new);

    }

    @Test
    public void testDistinct(){
        int[] arr = new int[]{1,1,1,2,2,2,2,3,3,3,4,4};

        Arrays.stream(arr).distinct().forEach(System.out::println);
    }

    @Test
    public void testSkip(){
        Stream<Integer> iterate = Stream.iterate(0, x -> x + 1).limit(10);
        System.out.println(iterate.skip(5).count());
    }

2.映射

方法描述
map
map(Function f)接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。
mapToDouble(ToDoubleFunction f)接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的 DoubleStream。
mapToInt(ToIntFunction f)接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的 IntStream。
mapToLong(ToLongFunction f)接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的 LongStream。
flatMap(Function f)接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流
    @Test
    public void testMap(){
        int[] arr = new int[]{1,2,3,4,5,6,7,8};

        Arrays.stream(arr).map(x->x*2).forEach(System.out::print);
        System.out.println();
        Arrays.stream(arr).mapToObj(x->"x"+x).forEach(System.out::print);
        System.out.println();
        Arrays.stream(arr).mapToLong(x->x).forEach(System.out::print);
        System.out.println();
        Arrays.stream(arr).mapToDouble(x->x).forEach(System.out::print);

        // flatMap 将多个流映射成一个流
        System.out.println();
        String[] strs = new String[]{"aaa","bbb","ccc"};
        Arrays.stream(strs).map(str->str.split("")).forEach(str-> System.out.println(Arrays.toString(str)));
        System.out.println();
        Arrays.stream(strs).map(str->str.split("")).flatMap(Arrays::stream).forEach(System.out::println);
        System.out.println();
        Arrays.stream(strs).map(str->str.split("")).flatMap(str->Arrays.stream(str)).forEach(System.out::println);

        System.out.println();
        Arrays.stream(strs).map(str->str.split("")).flatMapToInt(str-> IntStream.of(str.length)).forEach(System.out::println);

        System.out.println();
        String[] strs2 = new String[]{"a","b","c"};
        Arrays.stream(strs2).peek(String::toLowerCase).forEach(System.out::println);


        list.stream().peek(emp -> emp.setAge(emp.age+2)).forEach(emp -> System.out.println(emp.getName()+"-"+emp.getAge()));

    }

3.排序

方法描述
sorted()产生一个新流,其中按自然顺序排序
sorted(Comparator com)产生一个新流,其中按比较器顺序排序
    @Test
    public void sorted(){
        int[] arr =new int[]{3,2,1,6,5,4};

        Arrays.stream(arr).sorted().forEach(System.out::print);
        System.out.println();

        list.stream().sorted(new Comparator<Emp>() {
            @Override
            public int compare(Emp o1, Emp o2) {
                return o2.getAge()-o1.getAge();
            }
        }).forEach(emp -> System.out.println(emp.getName()+"-"+emp.getAge()+"-"+emp.getSalary()));
        System.out.println();
        
        list.stream().sorted((o1, o2) -> o2.getAge()-o1.getAge()).forEach(emp -> System.out.println(emp.getName()+"-"+emp.getAge()+"-"+emp.getSalary()));

    }
 public static List<Emp> list = new ArrayList<>();
    static {
        list.add(new Emp("xiaoHong1", 20, 1000.0));
        list.add(new Emp("xiaoHong2", 25, 2000.0));
        list.add(new Emp("xiaoHong3", 30, 3000.0));
        list.add(new Emp("xiaoHong4", 35, 4000.0));
        list.add(new Emp("xiaoHong5", 38, 5000.0));
        list.add(new Emp("xiaoHong6", 45, 9000.0));
        list.add(new Emp("xiaoHong7", 55, 10000.0));
        list.add(new Emp("xiaoHong8", 42, 15000.0));
    }


    public static class Emp {
        private String name;

        private Integer age;

        private Double salary;

        public Emp(String name, Integer age, Double salary) {
            super();
            this.name = name;
            this.age = age;
            this.salary = salary;
        }

        public String getName() {
            return name;
        }

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

        public Integer getAge() {
            return age;
        }

        public void setAge(Integer age) {
            this.age = age;
        }

        public Double getSalary() {
            return salary;
        }

        public void setSalary(Double salary) {
            this.salary = salary;
        }

    }

终止操作

  • 终端操作会从流的流水线生成结果。其结果可以是任何不是流的值,例
    如:List、Integer,甚至是 void 。
  • 流进行了终止操作后,不能再次使用。

1.匹配与查找

方法描述
allMatch(Predicate p)检查是否匹配所有元素
anyMatch(Predicate p)检查是否至少匹配一个元素
noneMatch(Predicate p)检查是否没有匹配所有元素
findFirst()返回第一个元素
findAny()返回当前流中的任意元素
count()返回流中元素总数
max(Comparator c)返回流中最大值
min(Comparator c)返回流中最小值
forEach(Consumer c)内部迭代(使用 Collection 接口需要用户去做迭代,称为外部迭代。相反Stream API 使用内部迭代——它帮你把迭代做了)

2.规约

方法描述
reduce(T iden, BinaryOperator b)可以将流中元素反复结合起来,得到一个值。返回 T
reduce(BinaryOperator b)可以将流中元素反复结合起来,得到一个值。返回 Optional
备注:map 和 reduce 的连接通常称为 map-reduce 模式,因 Google
用它来进行网络搜索而出名。
    @Test
    public void testReduce(){
        List<Integer> numbers = Stream.iterate(1, x -> x + 1).limit(10).collect(Collectors.toList());
        Integer aa = 0;
        for (Integer i : numbers) {
            aa += i;
        }
        //T reduce(T identity, BinaryOperator<T> accumulator);
        Integer sum1 = numbers.stream().reduce(0, (a, b) -> a + b);

        //Optional<T> reduce(BinaryOperator<T> accumulator);
        Optional<Integer> dd1 = numbers.stream().reduce((a, b) -> a + b);
        
        System.out.println(aa);
        System.out.println(sum1);
        System.out.println(dd1.get());
    }

3.收集

方法描述
collect(Collector c)将流转换为其他形式。接收一个 Collector接口的实现,用于给Stream中元素做汇总的方法
toArray(IntFunction<A[]> generator)将流转换成数组
collectingAndThen(Collector<T,A,R> downstream,Function<R,RR>finisher)对收集结果进行二次处理

       @Test
    public void testCollection(){
        //https://blog.csdn.net/weixin_43318134/article/details/104442023
        // 收集到List
        List<Integer> collect = Stream.iterate(0, x -> x + 1).limit(100).filter(x -> x % 2 == 0).collect(Collectors.toList());
        // 收集到set
        Set<Integer> set = Stream.iterate(0, x -> x + 1).limit(100).filter(x -> x % 2 == 0).collect(Collectors.toSet());

        // 收集到map
        Emp emp1 = new Emp("xiaoHong1", 20, 1000.0);
        Emp emp2 = new Emp("xiaoHong2", 18, 1100.0);
        /**
         * key
         * value
         * 解决键冲突
         * 返回类型,默认返回HashMap
         */
        Stream.of(emp1,emp2).collect(Collectors.toMap(Emp::getName,Emp::getAge,Integer::sum,TreeMap::new));

        // 收集到指定集合中
        ArrayList<Integer> arrayList = Stream.iterate(0, x -> x + 1).limit(100).filter(x -> x % 2 == 0).collect(Collectors.toCollection(ArrayList::new));
        // 收集到Object数组
        Object[] objects = Stream.iterate(0, x -> x + 1).limit(100).filter(x -> x % 2 == 0).toArray();
        // 收集到指定数组
        Integer[] integers = Stream.iterate(0, x -> x + 1).limit(100).filter(x -> x % 2 == 0).toArray(Integer[]::new);

        // 收集到String
        String string1 = Stream.of("1", "2", "3").collect(Collectors.joining()); // 123
        String string2 = Stream.of("1", "2", "3").collect(Collectors.joining(","));//1,2,3

        /*##############################分组收集################################*/
        Emp emp3 = new Emp("xiaoHong1", 20, 1100.0);
        Emp emp4 = new Emp("xiaoHong2", 18, 1200.0);
        Emp emp5 = new Emp("xiaoHong3", 20, 1300.0);
        Emp emp6 = new Emp("xiaoHong4", 18, 1400.0);
        Map<Integer, List<Emp>> collectGroupByAge = Stream.of(emp3, emp4,emp5,emp6).collect(Collectors.groupingBy(Emp::getAge));
        collectGroupByAge.forEach((key,value)->{
            System.out.println("age:"+key);
            value.forEach(emp -> System.out.println(emp.getName()+"-"+emp.getAge()+"-"+emp.getSalary()));
        });

        // 分组收集下游收集器-分组收集指定结果集存储类型
        Map<Integer, Set<Emp>> collectGroupByAsSet = Stream.of(emp3, emp4, emp5, emp6).collect(Collectors.groupingBy(Emp::getAge, Collectors.toSet()));
        // 分组收集下游收集器-对每组数量统计
        Map<Integer, Long> collectGroupByAgeAsCount = Stream.of(emp3, emp4, emp5, emp6).collect(Collectors.groupingBy(Emp::getAge, Collectors.counting()));
        // 分组收集下游收集器-分组后对对数值结果进行统计计算(最大值, 最小值, 平均值, 求和, 计数等)
        Map<Integer, DoubleSummaryStatistics> collectGroupByAgeAsSum = Stream.of(emp3, emp4, emp5, emp6).collect(Collectors.groupingBy(Emp::getAge, Collectors.summarizingDouble(Emp::getSalary)));
        collectGroupByAgeAsSum.forEach((key,value)->{
            System.out.println(key+"-"+value.getSum());
        });
        // 分组收集下游收集器-分组后对组内某一元素最小值
        Map<Integer, Optional<Emp>> collectGroupByAgeAsMin = Stream.of(emp3, emp4, emp5, emp6).collect(Collectors.groupingBy(Emp::getAge, Collectors.minBy(Comparator.comparing(Emp::getSalary))));
        collectGroupByAgeAsMin.forEach((key,value)->{
            System.out.println(key+"-"+value.get().getName()+"-"+value.get().getSalary());
        });

        // 分组收集下游收集器-分组后将结果映射为其他类型
        Map<Integer, String> collectGroupByAgeMapping = Stream.of(emp3, emp4, emp5, emp6).collect(Collectors.groupingBy(Emp::getAge, Collectors.mapping(emp -> emp.getName() + "-" + emp.getAge() + "-" + emp.getSalary(), Collectors.joining("|"))));
        collectGroupByAgeMapping.forEach((key,value)->{
            System.out.println(key+"-"+value);
        });
        

    }

    }

collectingAndThen举例

		//对集合的结果进行去重
        List<User> list = userList.stream()
                .collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(User::getUserId))), ArrayList::new));
        System.out.println(list);
        //查找工资最高的员工的姓名
        String userName = userList.stream()
                .collect(Collectors.collectingAndThen(Collectors.maxBy(Comparator.comparing(User::getSalary)),(Optional<User> user) -> user.map(User::getUserName).orElse(null)));
        System.out.println(userName);
		//计算用户工资的平均值
        Double avgSalary = userList.stream()
                .collect(Collectors.collectingAndThen(Collectors.averagingDouble(User::getSalary), Double::doubleValue));
        System.out.println(avgSalary);


流的分类

对象流

对象流即Stram。

基本类型流

对于基本数据类型, 有转门的流来处理, 如IntStream, DoubleStream, LongStream等。

    @Test
    public void testBaseStream(){
        // 创建基本流
        IntStream intStream1 = IntStream.of(3, 2, 1, 4, 5);
        IntStream intStream2 = Arrays.stream(new int[]{3, 4, 2, 1, 5});

		// 几个静态方法	
        IntStream.range(0,9).forEach(System.out::print); //[0,1...9]
        System.out.println();
        IntStream.rangeClosed(0,9).forEach(System.out::print);//[0,1...9]
        System.out.println();

        // 合并两个流
        IntStream.concat(intStream1,intStream2).forEach(System.out::print);
        System.out.println();

        // 获取Unicode码对应的值
        String s = "a";
        s.codePoints().forEach(System.out::println); // 97
        System.out.println();

        // 基本流转对象流
        Stream<Integer> boxed = IntStream.of(3, 2, 1).boxed();

        // 对象流转基本流
        IntStream intStream = Stream.of("3", "2", "1").mapToInt(Integer::parseInt);
        
    }

并行流

并行流就是把一个内容分成多个数据块,并用不同的线程分成多个数据块,并用不同的线程分别处理每个数据块的流。

    @Test
    public void testParallel(){
        // 获取并行流
        // Collection.parallelStream();
        // Stream.parallel();
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < 1000; i++) {
            list.add(i);
        }
        System.out.println(list.parallelStream().reduce(Integer::sum));
        System.out.println(IntStream.range(0, 1000).parallel().reduce((a, b) -> a + b));

    }

并行化的底层是fork/join
并行化会导致大量开销, 只有面对非常大的数据量时才划算
并行化使用的线程池有可能被像I/O或者网络访问之类的操作而堵塞

https://blog.csdn.net/qq_38974634/article/details/81347604

Optional

  • 到目前为止,臭名昭著的空指针异常是导致Java应用程序失败的最常见原因。以前,为了解决空指针异常,Google公司著名的Guava项目引入了Optional类,Guava通过使用检查空值的方式来防止代码污染,它鼓励程序员写更干净的代码。受到Google Guava的启发,Optional类已经成为Java 8类库的一部分。
  • Optional 类(java.util.Optional) 是一个容器类,它可以保存类型T的值,代表这个值存在。或者仅仅保存null,表示这个值不存在。原来用 null 表示一个值不存在,现在 Optional 可以更好的表达这个概念。并且可以避免空指针异常。
  • Optional类的Javadoc描述如下:这是一个可以为null的容器对象。如果值存在则isPresent()方法会返回true,调用get()方法会返回该对象。
创建Optional类对象的方法:
  • Optional.of(T t) : 创建一个 Optional 实例,t必须非空;
  • Optional.empty() : 创建一个空的 Optional 实例
  • Optional.ofNullable(T t):t可以为null
判断Optional容器中是否包含对象:
  • boolean isPresent() : 判断是否包含对象
  • void ifPresent(Consumer<? super T> consumer) :如果有值,就执行Consumer接口的实现代码,并且该值会作为参数传给它。
获取Optional容器的对象:
  • T get(): 如果调用对象包含值,返回该值,否则抛异常
  • T orElse(T other) :如果有值则将其返回,否则返回指定的other对象。
  • T orElseGet(Supplier<? extends T> other) :如果有值则将其返回,否则返回由Supplier接口实现提供的对象。
  • T orElseThrow(Supplier<? extends X> exceptionSupplier) :如果有值则将其返回,否则抛出由Supplier接口实现提供的异常。

新时间日期 API

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值