• java通过Stream对list集合分组


    java通过Stream对list集合分组

    现在有一个List集合,想对该集合中的数据分组处理,想到java8中的stream,就搞来试试,非常给力!例子如下

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
     
    package com.maps;
     
    public class User{
    private Integer id;
    private String type;
    private String name;
     
    public User(){}
    public User(Integer id,String type,String name){
    this.id = id;
    this.type = type;
    this.name = name;
    }
     
    public void setId(Integer id){
    this.id = id;
    }
     
    public Integer getId(){
    return id;
    }
     
    public void setType(String type){
    this.type = type;
    }
     
    public String getType(){
    return type;
    }
     
    public void setName(String name){
    this.name = name;
    }
     
    public String getName(){
    return name;
    }
    }
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
     
    package com.maps;
     
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;
    import java.util.stream.Collectors;
     
    public class MainUser{
     
    public static void main(String[] args){
    List<User> list = getUserList();
    Map<String,List<User>> userGroupMap = list.stream().collect(Collectors.groupingBy(User::getType));
    }
     
     
    public static List<User> getUserList(){
    User user1 = new User(1,"张三","小学");
    User user2 = new User(2,"李四","小学");
    User user3 = new User(3,"王五","初中");
    User user4 = new User(4,"马六","高中");
     
    List<User> list = new ArrayList<User>();
    list.add(user1);
    list.add(user2);
    list.add(user3);
    list.add(user4);
     
    return list;
    }
    }

    运行上面例子得到下面的结果

    1
    {高中=[com.maps.User@448139f0], 初中=[com.maps.User@7cca494b], 小学=[com.maps.User@7ba
  • 相关阅读:
    正则表达式--断言
    ie6兼容性处理
    git log 高级用法
    html-文件上传设置accept类型延时问题
    sublime text3 -- JavaScript Completions
    Git进行fork后如何与原仓库同步
    Redis的数据结构及应用场景
    PHP手册-函数参考-日期与时间相关扩展
    什么是缓存
    MySQL的连接方式、事务、性能优化
  • 原文地址:https://www.cnblogs.com/mr-wuxiansheng/p/7911626.html
Copyright © 2020-2023  润新知