zoukankan      html  css  js  c++  java
  • JAVA在JDK1.8中Stream流的使用

    Stream流的map使用

    转换大写

     List<String> list3 = Arrays.asList("zhangSan", "liSi", "wangWu");
     System.out.println("转换之前的数据:" + list3);
     List<String> list4 = list3.stream().map(String::toUpperCase).collect(Collectors.toList());
     System.out.println("转换之后的数据:" + list4); 
     // 转换之后的数据:[ZHANGSAN, LISI,WANGWU]

    转换数据类型

    List<String> list31 = Arrays.asList("1", "2", "3");
     System.out.println("转换之前的数据:" + list31);
     List<Integer> list41 = list31.stream().map(Integer::valueOf).collect(Collectors.toList());
     System.out.println("转换之后的数据:" + list41); 
     // [1, 2, 3]

    获取平方

    List<Integer> list5 = Arrays.asList(new Integer[] { 1, 2, 3, 4, 5 });
     List<Integer> list6 = list5.stream().map(n -> n * n).collect(Collectors.toList());
     System.out.println("平方的数据:" + list6);
     // [1, 4, 9, 16, 25]

    Stream流的filter使用  用于通过设置的条件过滤出元素

    通过与 findAny 得到 if/else 的值

    List<String> list = Arrays.asList("张三", "李四", "王五", "xuwujing");
    String result3 = list.stream().filter(str -> "李四".equals(str)).findAny().orElse("找不到!");
    String result4 = list.stream().filter(str -> "李二".equals(str)).findAny().orElse("找不到!");
    
    System.out.println("stream 过滤之后 2:" + result3);
    System.out.println("stream 过滤之后 3:" + result4);
    //stream 过滤之后 2:李四
    //stream 过滤之后 3:找不到!

    通过与 mapToInt 计算和

     List<User> lists = new ArrayList<User>();
     lists.add(new User(6, "张三"));
     lists.add(new User(2, "李四"));
     lists.add(new User(3, "王五"));
     lists.add(new User(1, "张三"));
     // 计算这个list中出现 "张三" id的值
     int sum = lists.stream().filter(u -> "张三".equals(u.getName())).mapToInt(u -> u.getId()).sum();
    
     System.out.println("计算结果:" + sum); 
     // 7

    Stream流的flatMap使用   用于映射每个元素到对应的结果,一对多。

    从句子中得到单词

     String worlds = "The way of the future";
     List<String> list7 = new ArrayList<>();
     list7.add(worlds);
     List<String> list8 = list7.stream().flatMap(str -> Stream.of(str.split(" ")))
       .filter(world -> world.length() > 0).collect(Collectors.toList());
     System.out.println("单词:");
     list8.forEach(System.out::println);
     // 单词:
     // The 
     // way 
     // of 
     // the 
     // future

    Stream流的limit使用 用于获取指定数量的流

    获取前n条数的数据

     Random rd = new Random();
     System.out.println("取到的前三条数据:");
     rd.ints().limit(3).forEach(System.out::println);
     // 取到的前三条数据:
     // 1167267754
     // -1164558977
     // 1977868798

    结合skip使用得到需要的数据

    skip表示的是扔掉前n个元素。

    List<User> list9 = new ArrayList<User>();
     for (int i = 1; i < 4; i++) {
      User user = new User(i, "pancm" + i);
      list9.add(user);
     }
     System.out.println("截取之前的数据:");
     // 取前3条数据,但是扔掉了前面的2条,可以理解为拿到的数据为 2<=i<3 (i 是数值下标)
     List<String> list10 = list9.stream().map(User::getName).limit(3).skip(2).collect(Collectors.toList());
     System.out.println("截取之后的数据:" + list10);
     //  截取之前的数据:
     //  姓名:pancm1
     //  姓名:pancm2
     //  姓名:pancm3
     //  截取之后的数据:[pancm3]

    Stream流的sort使用

    Random rd2 = new Random();
     System.out.println("取到的前三条数据然后进行排序:");
     rd2.ints().limit(3).sorted().forEach(System.out::println);
     // 取到的前三条数据然后进行排序:
     // -2043456377
     // -1778595703
     // 1013369565

    优化排序

    //普通的排序取值
     List<User> list11 = list9.stream().sorted((u1, u2) -> u1.getName().compareTo(u2.getName())).limit(3)
       .collect(Collectors.toList());
     System.out.println("排序之后的数据:" + list11);
     //优化排序取值
     List<User> list12 = list9.stream().limit(3).sorted((u1, u2) -> u1.getName().compareTo(u2.getName()))
       .collect(Collectors.toList());
     System.out.println("优化排序之后的数据:" + list12);
     //排序之后的数据:[{"id":1,"name":"pancm1"}, {"id":2,"name":"pancm2"}, {"id":3,"name":"pancm3"}]
     //优化排序之后的数据:[{"id":1,"name":"pancm1"}, {"id":2,"name":"pancm2"}, {"id":3,"name":"pancm3"}]

    Stream流的max/min/distinct使用

    得到最大最小值

    List<String> list13 = Arrays.asList("zhangsan","lisi","wangwu","xuwujing");
     int maxLines = list13.stream().mapToInt(String::length).max().getAsInt();
     int minLines = list13.stream().mapToInt(String::length).min().getAsInt();
     System.out.println("最长字符的长度:" + maxLines+",最短字符的长度:"+minLines);
     //最长字符的长度:8,最短字符的长度:4

    得到去重之后的数据

     String lines = "good good study day day up";
     List<String> list14 = new ArrayList<String>();
     list14.add(lines);
     List<String> words = list14.stream().flatMap(line -> Stream.of(line.split(" "))).filter(word -> word.length() > 0)
       .map(String::toLowerCase).distinct().sorted().collect(Collectors.toList());
     System.out.println("去重复之后:" + words);
     //去重复之后:[day, good, study, up]

    Stream流的Match使用

    • allMatch:Stream 中全部元素符合则返回 true ;
    • anyMatch:Stream 中只要有一个元素符合则返回 true;
    • noneMatch:Stream 中没有一个元素符合则返回 true。

    数据是否符合

     boolean all = lists.stream().allMatch(u -> u.getId() > 3);
     System.out.println("是否都大于3:" + all);
     boolean any = lists.stream().anyMatch(u -> u.getId() > 3);
     System.out.println("是否有一个大于3:" + any);
     boolean none = lists.stream().noneMatch(u -> u.getId() > 3);
     System.out.println("是否没有一个大于3的:" + none);  
     // 是否都大于3:false
     // 是否有一个大于3:true
     // 是否没有一个大于3的:false

    Stream流的reduce使用 主要作用是把 Stream 元素组合起来进行操作。

    字符串连接

    String concat = Stream.of("A", "B", "C", "D").reduce("", String::concat);
    System.out.println("字符串拼接:" + concat);

    得到最小值

     double minValue = Stream.of(-4.0, 1.0, 3.0, -2.0).reduce(Double.MAX_VALUE, Double::min);
     System.out.println("最小值:" + minValue);
     //最小值:-4.0

    求和

    // 求和, 无起始值
     int sumValue = Stream.of(1, 2, 3, 4).reduce(Integer::sum).get();
     System.out.println("有无起始值求和:" + sumValue);
     // 求和, 有起始值
      sumValue = Stream.of(1, 2, 3, 4).reduce(1, Integer::sum);
      System.out.println("有起始值求和:" + sumValue);
     // 有无起始值求和:10
     // 有起始值求和:11

    过滤拼接

    concat = Stream.of("a", "B", "c", "D", "e", "F").filter(x -> x.compareTo("Z") > 0).reduce("", String::concat);
    System.out.println("过滤和字符串连接:" + concat);
     //过滤和字符串连接:ace

    Stream流的groupingBy/partitioningBy使用

    • groupingBy:分组排序;
    • partitioningBy:分区排序。

    分组排序

    System.out.println("通过id进行分组排序:");
     Map<Integer, List<User>> personGroups = Stream.generate(new UserSupplier2()).limit(5)
       .collect(Collectors.groupingBy(User::getId));
     Iterator it = personGroups.entrySet().iterator();
     while (it.hasNext()) {
      Map.Entry<Integer, List<User>> persons = (Map.Entry) it.next();
      System.out.println("id " + persons.getKey() + " = " + persons.getValue());
     }
     
     // 通过id进行分组排序:
     // id 10 = [{"id":10,"name":"pancm1"}] 
     // id 11 = [{"id":11,"name":"pancm3"}, {"id":11,"name":"pancm6"}, {"id":11,"name":"pancm4"}, {"id":11,"name":"pancm7"}]
    
    
    
     class UserSupplier2 implements Supplier<User> {
      private int index = 10;
      private Random random = new Random();
     
      @Override
      public User get() {
       return new User(index % 2 == 0 ? index++ : index, "pancm" + random.nextInt(10));
      }
     }

    分区排序

     System.out.println("通过年龄进行分区排序:");
     Map<Boolean, List<User>> children = Stream.generate(new UserSupplier3()).limit(5)
       .collect(Collectors.partitioningBy(p -> p.getId() < 18));
    
     System.out.println("小孩: " + children.get(true));
     System.out.println("成年人: " + children.get(false));
     
     // 通过年龄进行分区排序:
     // 小孩: [{"id":16,"name":"pancm7"}, {"id":17,"name":"pancm2"}]
     // 成年人: [{"id":18,"name":"pancm4"}, {"id":19,"name":"pancm9"}, {"id":20,"name":"pancm6"}]
    
      class UserSupplier3 implements Supplier<User> {
      private int index = 16;
      private Random random = new Random();
     
      @Override
      public User get() {
       return new User(index++, "pancm" + random.nextInt(10));
      }
     }

    Stream流的summaryStatistics使用  IntSummaryStatistics 用于收集统计信息(如count、min、max、sum和average)的状态对象。

    得到最大、最小、之和以及平均数。

     List<Integer> numbers = Arrays.asList(1, 5, 7, 3, 9);
     IntSummaryStatistics stats = numbers.stream().mapToInt((x) -> x).summaryStatistics();
      
     System.out.println("列表中最大的数 : " + stats.getMax());
     System.out.println("列表中最小的数 : " + stats.getMin());
     System.out.println("所有数之和 : " + stats.getSum());
     System.out.println("平均数 : " + stats.getAverage());
     
     // 列表中最大的数 : 9
     // 列表中最小的数 : 1
     // 所有数之和 : 25
     // 平均数 : 5.0
  • 相关阅读:
    Android应用之个人应用软件开发(2)【签到功能和记账】
    抽象类判断日期能否被2整除
    Android应用之个人应用软件开发(3)【SQLite数据库及理财功能实现】
    移动终端网页游戏移植研发框架【服务器及客户端交互处理】
    DirectX学习资料
    列宁的故事
    Managed DirectX +C# 开发(入门篇)(七)
    Managed DirectX +C# 开发(入门篇)(六)
    Managed DirectX +C# 开发(入门篇)(三)
    C#不同窗口类中的变量相互调用
  • 原文地址:https://www.cnblogs.com/pxblog/p/13453731.html
Copyright © 2011-2022 走看看