zoukankan      html  css  js  c++  java
  • JDK1.8 新特性(全)

    • Lambda表达式
    • 函数式接口
    • *方法引用和构造器调用
    • Stream API
    • 接口中的默认方法和静态方法
    • 新时间日期API

    Lambda表达式

     定义过滤方法:

    public List<Product> filterProductByPredicate(List<Product> list,MyPredicate<Product> mp){
            List<Product> prods = new ArrayList<>();
            for (Product prod : list){
                if (mp.test(prod)){
                    prods.add(prod);
                }
            }
            return prods;
        }

    使用lambda表达式进行过滤

    @Test
    public void test4(){
          List<Product> products = filterProductByPredicate(proList, (p) -> p.getPrice() < 8000);
          for (Product pro : products){
              System.out.println(pro);
          }
      }

    使用Stream API

    // 使用jdk1.8中的Stream API进行集合的操作
    @Test
    public void test(){
        // 根据价格过滤
        proList.stream()
               .fliter((p) -> p.getPrice() <8000)
               .limit(2)
               .forEach(System.out::println);
    
        // 根据颜色过滤
        proList.stream()
               .fliter((p) -> "红色".equals(p.getColor()))
               .forEach(System.out::println);
    
        // 遍历输出商品名称
        proList.stream()
               .map(Product::getName)
               .forEach(System.out::println);
    }

    Lmabda表达式的语法总结: () -> ();

    前置 语法
    无参数无返回值 () -> System.out.println(“Hello WOrld”)
    有一个参数无返回值 (x) -> System.out.println(x)
    有且只有一个参数无返回值 x -> System.out.println(x)
    有多个参数,有返回值,有多条lambda体语句 (x,y) -> {System.out.println(“xxx”);return xxxx;};
    有多个参数,有返回值,只有一条lambda体语句 (x,y) -> xxxx

    Stream API

    stream的创建

    // 1,校验通过Collection 系列集合提供的stream()或者paralleStream()
        List<String> list = new ArrayList<>();
        Strean<String> stream1 = list.stream();
    
        // 2.通过Arrays的静态方法stream()获取数组流
        String[] str = new String[10];
        Stream<String> stream2 = Arrays.stream(str);
    
        // 3.通过Stream类中的静态方法of
        Stream<String> stream3 = Stream.of("aa","bb","cc");
    
        // 4.创建无限流
        // 迭代
        Stream<Integer> stream4 = Stream.iterate(0,(x) -> x+2);
    
        //生成
        Stream.generate(() ->Math.random());

    Stream的中间操作:

    /**
       * 筛选 过滤  去重
       */
      emps.stream()
              .filter(e -> e.getAge() > 10)
              .limit(4)
              .skip(4)
              // 需要流中的元素重写hashCode和equals方法
              .distinct()
              .forEach(System.out::println);
    
    
      /**
       *  生成新的流 通过map映射
       */
      emps.stream()
              .map((e) -> e.getAge())
              .forEach(System.out::println);
    
    
      /**
       *  自然排序  定制排序
       */
      emps.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);

    Stream的终止操作:

    /**
             *      查找和匹配
             *          allMatch-检查是否匹配所有元素
             *          anyMatch-检查是否至少匹配一个元素
             *          noneMatch-检查是否没有匹配所有元素
             *          findFirst-返回第一个元素
             *          findAny-返回当前流中的任意元素
             *          count-返回流中元素的总个数
             *          max-返回流中最大值
             *          min-返回流中最小值
             */
    
            /**
             *  检查是否匹配元素
             */
            boolean b1 = emps.stream()
                    .allMatch((e) -> e.getStatus().equals(Employee.Status.BUSY));
            System.out.println(b1);
    
            boolean b2 = emps.stream()
                    .anyMatch((e) -> e.getStatus().equals(Employee.Status.BUSY));
            System.out.println(b2);
    
            boolean b3 = emps.stream()
                    .noneMatch((e) -> e.getStatus().equals(Employee.Status.BUSY));
            System.out.println(b3);
    
            Optional<Employee> opt = emps.stream()
                    .findFirst();
            System.out.println(opt.get());
    
            // 并行流
            Optional<Employee> opt2 = emps.parallelStream()
                    .findAny();
            System.out.println(opt2.get());
    
            long count = emps.stream()
                    .count();
            System.out.println(count);
    
            Optional<Employee> max = emps.stream()
                    .max((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()));
            System.out.println(max.get());
    
            Optional<Employee> min = emps.stream()
                    .min((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()));
            System.out.println(min.get());

    还有功能比较强大的两个终止操作 reduce和collect
    reduce操作: reduce:(T identity,BinaryOperator)/reduce(BinaryOperator)-可以将流中元素反复结合起来,得到一个值

     /**
             *  reduce :规约操作
             */
            List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
            Integer count2 = list.stream()
                    .reduce(0, (x, y) -> x + y);
            System.out.println(count2);
    
            Optional<Double> sum = emps.stream()
                    .map(Employee::getSalary)
                    .reduce(Double::sum);
            System.out.println(sum);

    collect操作:Collect-将流转换为其他形式,接收一个Collection接口的实现,用于给Stream中元素做汇总的方法

       /**
             *  collect:收集操作
             */
    
            List<Integer> ageList = emps.stream()
                    .map(Employee::getAge)
                    .collect(Collectors.toList());
            ageList.stream().forEach(System.out::println);
  • 相关阅读:
    基于贝叶斯概率模型的单幅图像去运动模糊算法
    Hihocoder 1067 最近公共祖先二
    HDU 2855 Fibonacci Check-up 矩阵
    HDU 2276 Kiki & Little Kiki 2 矩阵
    HDU 3483 A Very Simple Problem 矩阵构造
    HDU 2807 The Shortest Path 矩阵 + Floyd
    HDU 5015 233 Matrix 矩阵快速幂
    ZOJ 3497 Mistwald 矩阵
    POJ 3233 Matrix Power Series 矩阵等比数列求和
    HDU 2157 How many ways?? 矩阵
  • 原文地址:https://www.cnblogs.com/yi-yun/p/13497243.html
Copyright © 2011-2022 走看看