zoukankan      html  css  js  c++  java
  • Java8新特性Stream流的常见用法

    准备工作

    @Data
    public class Customer {
        private Long id;
        private String username;
        private Integer age;
        private String address;
    }
    
    public static List<Customer> initCustomer() {
        ArrayList<Customer> customerList = new ArrayList<>();
        Customer customer1 = new Customer(10L, "张三", 20, "中国");
        Customer customer2 = new Customer(11L, "李四", 20, "中国");
        Customer customer3 = new Customer(12L, "王二", 22, "中国");
        Customer customer4 = new Customer(13L, "jack", 23, "英国");
        Customer customer5 = new Customer(14L, "tom", 24, "英国");
        customerList.add(customer1);
        customerList.add(customer2);
        customerList.add(customer3);
        customerList.add(customer4);
        customerList.add(customer5);
        return customerList;
    }
    

    filter 筛选

    @Test
    public void filterTest() {
        List<Customer> customers = SpringbootInitApplicationTests.initCustomer();
        // 筛选在中国的,并且年龄小于22的客户
        List<Customer> result = customers.stream()
                .filter(customer -> customer.getAddress().equals("中国"))
                .filter(customer -> customer.getAge() < 22)
                .collect(Collectors.toList());
        System.out.println(result);
    }
    
     [
       Customer {
          id = 10, username = '张三', age = 20, address = '中国'
       },
       Customer {
          id = 11, username = '李四', age = 21, address = '中国'
       }
    ]
    

    distinct 去重

    @Test
    public void distinctTest() {
        List<String> list = Arrays.asList("a", "b", "c", "d", "b");
        List<String> collect = list.stream()
                .distinct()
                .collect(Collectors.toList());
        // [a, b, c, d]
        System.out.println(collect);
    }
    

    map 转换

    @Test
    public void mapTest() {
        List<Customer> customers = SpringbootInitApplicationTests.initCustomer();
        // 只把所有的年龄提取出来放在一个List集合中
        List<Integer> collect = customers.stream()
                .map(Customer::getAge)
                .collect(Collectors.toList());
        // [20, 21, 22, 23, 24]
        System.out.println(collect);
    }
    

    anyMatch 任意匹配

    只要有流中有一条匹配就返回true

    @Test
    public void anyMatchTest() {
        List<Customer> customers = SpringbootInitApplicationTests.initCustomer();
        // 任意英国的客户
        boolean flag = customers.stream()
                .anyMatch(customer -> customer.getAddress().equals("英国"));
        //true
        System.out.println(flag);
    }
    

    count 数量

    @Test
    public void countTest() {
        List<Customer> customers = SpringbootInitApplicationTests.initCustomer();
        // 以下三种都是求数量的
        Long collect = customers.stream().collect(Collectors.counting());
        int size = customers.size();
        long count = customers.stream().count();
        // 5==5==5
        System.out.println(collect + "==" + size + "==" + count);
    }
    

    最大值,最小值,平均值,总和,数量

    @Test
    public void summarizingTest() {
        List<Customer> customers = SpringbootInitApplicationTests.initCustomer();
        DoubleSummaryStatistics collect = customers.stream().collect(Collectors.summarizingDouble(Customer::getAge));
        // 24.0
        System.out.println(collect.getMax());
        // 20.0
        System.out.println(collect.getMin());
        // 22.0
        System.out.println(collect.getAverage());
        // 110.0
        System.out.println(collect.getSum());
        // 5
        System.out.println(collect.getCount());
    }
    

    join 以指定的字符串做拼接

    @Test
    public void joinTest() {
        List<Customer> customers = SpringbootInitApplicationTests.initCustomer();
        // 把所有客户的名字用逗号隔开拼接起来
        String collect = customers.stream()
                .map(Customer::getUsername)
                .collect(Collectors.joining(","));
        // 张三,李四,王二,jack,tom
        System.out.println(collect);
    }
    

    groupingBy 分组

    @Test
    public void groupingByTest() {
        List<Customer> customers = SpringbootInitApplicationTests.initCustomer();
        // 按照国家分组
        Map<String, List<Customer>> collect = customers.stream()
                .collect(Collectors.groupingBy(Customer::getAddress));
        System.out.println(collect);
    }
    
     {
       中国 = [Customer {
                id = 10, username = '张三', age = 20, address = '中国'
             },
             Customer {
                id = 11, username = '李四', age = 21, address = '中国'
             },
             Customer {
                id = 12, username = '王二', age = 22, address = '中国'
             }
          ],
      英国 = [Customer {
                id = 13, username = 'jack', age = 23, address = '英国'
             },
             Customer {
                id = 14, username = 'tom', age = 24, address = '英国'
             }
          ]
    }
    

    多级分组

    @Test
    public void moreGroupingByTest() {
        List<Customer> customers = SpringbootInitApplicationTests.initCustomer();
        // 先按照国家分组,再按照年龄分组
        Map<String, Map<Integer, List<Customer>>> collect = customers.stream()
                .collect(Collectors.groupingBy(Customer::getAddress, Collectors.groupingBy(Customer::getAge)));
        System.out.println(collect);
    }
    
     {
       中国 = {
             20 = [Customer {
                id = 10, username = '张三', age = 20, address = '中国'
             }, Customer {
                id = 11, username = '李四', age = 20, address = '中国'
             }],
             22 = [Customer {
                id = 12, username = '王二', age = 22, address = '中国'
             }]
          },
       英国 = {
             23 = [Customer {
                id = 13, username = 'jack', age = 23, address = '英国'
             }],
             24 = [Customer {
                id = 14, username = 'tom', age = 24, address = '英国'
             }]
          }
    }
    

    收集为list (set)类似

    @Test
    public void toListTest() {
        List<Customer> customers = SpringbootInitApplicationTests.initCustomer();
        List<String> collect = customers.stream()
                .map(Customer::getUsername)
                .collect(Collectors.toList());
        // [张三, 李四, 王二, jack, tom]
        System.out.println(collect);
    }
    

    toMap 将list转换成map

    @Test
    public void toMapTest() {
        List<Customer> customers = SpringbootInitApplicationTests.initCustomer();
        // 把客户id作为key,客户整体信息作为value
        Map<Long, Customer> collect = customers.stream().collect(Collectors.toMap(Customer::getId, v -> v));
        System.out.println(collect);
    }
    
     {
       10 = Customer {
          id = 10, username = '张三', age = 20, address = '中国'
       }, 11 = Customer {
          id = 11, username = '李四', age = 20, address = '中国'
       }, 12 = Customer {
          id = 12, username = '王二', age = 22, address = '中国'
       }, 13 = Customer {
          id = 13, username = 'jack', age = 23, address = '英国'
       }, 14 = Customer {
          id = 14, username = 'tom', age = 24, address = '英国'
       }
    }
    

    返回树形结构数据

    注意:这里我们的权限上下级之间以pid来关联,pid是指上一级权限的id,顶级权限的id为0。

    创建实体类

    // 表数据实体类
    @Data
    public class UmsPermission implements Serializable {
      	// 主键id
        private Long id;
      	// 父id
        private Long pid;
      	// 名称
        private String name;
        private String value;
    }
    
    // 组织成树结构的实体类
    @Data
    public class UmsPermissionNode extends UmsPermission{
        private List<UmsPermissionNode> children;
    }
    

    造数据

    private List<UmsPermission> initUmPermissions() {
        ArrayList<UmsPermission> umsPermissions = new ArrayList<>();
        UmsPermission u1 = new UmsPermission(1L, 0L, "数据采集", "select1");
        UmsPermission u2 = new UmsPermission(2L, 0L, "标准维护", "select2");
        UmsPermission u3 = new UmsPermission(3L, 1L, "采集子集", "select3");
        UmsPermission u4 = new UmsPermission(4L, 2L, "维护子集", "select4");
        umsPermissions.add(u1);
        umsPermissions.add(u2);
        umsPermissions.add(u3);
        umsPermissions.add(u4);
        return umsPermissions;
    }
    

    接口

    /**
     * 组织成树状结构
     */
    @GetMapping("/treeList")
    public List<UmsPermissionNode> treeList() {
        // 查询数据
        List<UmsPermission> permissionList = initUmPermissions();
        List<UmsPermissionNode> result = permissionList.stream()
                // 提取pid = 0 的数据
                .filter(permission -> permission.getPid().equals(0L))
                // 第一个参数为pid=0的父级列表 第二个参数为全部数据
                .map(permission -> covert(permission, permissionList)).collect(Collectors.toList());
        return result;
    }
    
    /**
     * 将权限转换为带有子级的权限对象
     * 当找不到子级权限的时候map操作不会再递归调用covert
     */
    private UmsPermissionNode covert(UmsPermission permission, List<UmsPermission> permissionList) {
        UmsPermissionNode node = new UmsPermissionNode();
        BeanUtils.copyProperties(permission, node);
        List<UmsPermissionNode> children = permissionList.stream()
                // 遍历所有数据的pid跟这个过滤过得进来的这个父级id做对比,如果相同就继续下一步,如果没有相同的就结束这个递归
                // 然后从最底层的开始走.collect(Collectors.toList(),node.setChildren(children),最后组织成一个树状结构
                .filter(subPermission -> subPermission.getPid().equals(permission.getId()))
                // 第一个参数是当前的父级数据 第二个参数为全部数据
                .map(subPermission -> covert(subPermission, permissionList)).collect(Collectors.toList());
        node.setChildren(children);
        return node;
    }
    

    返回的json结构

    // http://localhost:8080/treeList
    [
      {
        "id": 1,
        "pid": 0,
        "name": "数据采集",
        "value": "select1",
        "children": [
          {
            "id": 3,
            "pid": 1,
            "name": "采集子集",
            "value": "select3",
            "children": [
              
            ]
          }
        ]
      },
      {
        "id": 2,
        "pid": 0,
        "name": "标准维护",
        "value": "select2",
        "children": [
          {
            "id": 4,
            "pid": 2,
            "name": "维护子集",
            "value": "select4",
            "children": [
              
            ]
          }
        ]
      }
    ]
    
  • 相关阅读:
    阿里云与物理服务器
    ## 100个网路基础知识##
    Linux 中vim编辑器
    Linux 目录结构及增删改查
    Linux 命令行常用快捷键
    XSS劫持cookie登录
    Tomcat
    centos 6.5 搭建DHCP实验
    centos 6.5 系统故障分析实验
    LVM的创建及管理
  • 原文地址:https://www.cnblogs.com/sun2020/p/13970591.html
Copyright © 2011-2022 走看看