本篇文章小编给大家分享一下List集合按某个属性或者字段进行分组操作代码,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
List集合按某个属性或者字段进行分组
List
核心代码
Map> collect = stuList.stream().collect(Collectors.groupingBy(Student::getInstitution));
实现代码示例:
public static void main(String[] args) { ListstuList=initStuList2(); Map > collect = stuList.stream().collect(Collectors.groupingBy(Student::getInstitution)); for(String key:collect.keySet()){ System.out.println(key+":" +collect.get(key).size()); System.out.println(collect.get(key)); } } public static List initStuList2(){ List stuList=new ArrayList (1000); for(int i=0;i<10;i++){ Student student = new Student(); long stu=(long) ((Math.random()*9+10000)*1000000); String Idcard=String.valueOf(stu).substring(0, 9); String ids=UUID.randomUUID().toString().replaceAll("-",""); student.setId(ids); student.setUsername("student"+i); student.setClasses("计算机"+i); student.setIdcard("362425199"+Idcard); String [] institution={"信息学院","文学院","音乐学院","体院","理学院","机电学院"}; int ss=(int)(Math.random()*6); student.setInstitution(institution[ss]); student.setMobile("18179"+Idcard.substring(0, 6)); student.setEmail(Idcard+"@qq.com"); student.setQq(Idcard); student.setHomeaddress("广东省深圳市"); student.setWeixin(Idcard); if(i%50==0){student.setSex("广东省深圳市");} else{ String[] sexs={"男","女"}; int ii=((int) Math.random()); student.setSex(sexs[ii]); } student.setCreateby("拿破仑"); student.setCreatetime(new Date()); stuList.add(student); } return stuList; }
实现效果
按照学院分组,得到体院集合中6个对象,文学院2个对象,理学院1个对象,信息学院1个对象
List
核心代码:
Map>> gslist = agentList.stream().collect(Collectors.groupingBy(e -> e.get("sex").toString()));
实现代码示例
public static void main(String[] args) { List
实现效果
List分组的两种方式
java8之前List分组
假设有个student类,有id、name、score属性,list集合中存放所有学生信息,现在要根据学生姓名进行分组。
public Map> groupList(List students) { Map > map = new Hash<>(); for (Student student : students) { List tmpList = map.get(student.getName()); if (tmpList == null) { tmpList = new ArrayList<>(); tmpList.add(student); map.put(student.getName(), tmpList); } else { tmpList.add(student); } } return map; }
java8的List分组
public Map> groupList(List students) { Map > map = students.stream().collect(Collectors.groupingBy(Student::getName)); return map; }