List集合按某个属性或者字段进行分组的操作

List集合按某个属性或者字段进行分组

List<Object>分组 按照Student对象中的Institution(学院)属性进行分组统计

核心代码

Map<String, List<Student>> collect = stuList.stream().collect(Collectors.groupingBy(Student::getInstitution));

实现代码示例:

public static void main(String[] args) {
  List<Student> stuList=initStuList2();
  Map<String, List<Student>> 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<Student> initStuList2(){
  List<Student> stuList=new ArrayList<Student>(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<String,Object>>分组统计 根据性别分类

核心代码:

Map<String, List<Map<String, Object>>> gslist = agentList.stream().collect(Collectors.groupingBy(e -> e.get("sex").toString()));

实现代码示例

public static void main(String[] args) {
		List<Map<String,Object>> agentList=init();
		HashMap<String, Object> hashMap =(HashMap<String, Object>) agentList.get(0);
		Map<String, List<Map<String, Object>>> gslist = agentList.stream().collect(Collectors.groupingBy(e -> e.get("sex").toString()));
		for(String key:gslist.keySet()){
	    	System.out.println(key+" : "+gslist.get(key).size());
	    	System.out.println(gslist.get(key));
	    }
	}

	/***
	 * 初始化联系信�?
	 * @return
	 */
	public static  List<Map<String,Object>> init(){
		String insertID=UUID.randomUUID().toString().replaceAll("-","");
		List<Map<String,Object>> concacts= new ArrayList<Map<String,Object>>();
		long time1=System.currentTimeMillis();
		for(int i=0;i<10;i++){
			String id=UUID.randomUUID().toString().replaceAll("-","");
			Map<String, Object> map = new HashMap<String,Object>();
			map.put("id", id);
			map.put("name", "张三");
			map.put("identity_no", "36242519961225"+(int)(Math.random()*10000+1000));
			map.put("telphone","1852562"+(int)(Math.random()*10000+1000));
			map.put("address","江西吉安");
			map.put("levels", "VIP");
			map.put("source", 0);
			map.put("flight_no", "ZH9101");
			map.put("planned_takeofftime", "1220");
			map.put("estimated_takeofftime", "1425");
			map.put("flight_change_type", 1);
			map.put("flight_change_reason", "军事活动");
			map.put("flightdate","2019-05-01");
			map.put("en_name", "ZHANG/SAN");
			map.put("traveller_idx", (int)(Math.random()*1000+100));
			String [] sexs={"男","女","同性恋","人妖"};
			int kk=(int) (Math.random()*4);
			map.put("sex", sexs[kk]);
			map.put("phone_num","1302880"+(int)(Math.random()*10000+1000));
			map.put("originating", "SZX");
			map.put("terminus", "BKK");
			map.put("ticketid", (int)(Math.random()*10000+1000));
			map.put("mainspace", "J");
			map.put("sonspace", "C");
			map.put("message_info", "4");
			map.put("extension", "1892562"+(int)(Math.random()*10000+1000));
			map.put("officeid", (int)(Math.random()*10000+1000));
			map.put("pnrics", (int)(Math.random()*10000+1000));
			map.put("traveller_safe", "2019-02-23 ZH9007");
			map.put("phone_inform", 1);
			concacts.add(map);
		}
		long time2=System.currentTimeMillis();
		//System.out.println("初始化数据花�?"+(time2-time1)/1000);
		return concacts;
	}	

实现效果

List分组的两种方式

java8之前List分组

假设有个student类,有id、name、score属性,list集合中存放所有学生信息,现在要根据学生姓名进行分组。

public Map<String, List<Student>> groupList(List<Student> students) {
 Map<String, List<Student>> map = new Hash<>();
 for (Student student : students) {
  List<Student> 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<String, List<Student>> groupList(List<Student> students) {
 Map<String, List<Student>> map = students.stream().collect(Collectors.groupingBy(Student::getName));
 return map;
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • java ArrayList按照同一属性进行分组

    java ArrayList按照同一属性进行分组 前言: 通常使用SQL查询一批数据的时候,可以利用SQL中的GROUP BY语句对数据进行分组,但是有时候出于对性能的考虑,不会使用GROUP BY,而是先把数据捞出来后,使用代码,在内存中按照某个属性进行分组. 代码 public class SkuVo { private Long skuId; private String productName; private Long brandStoreSn; public SkuVo(Long s

  • Java 将List中的实体类按照某个字段进行分组并存放至Map中操作

    1.JDK1.8之前: 假设有实体类User,里面有字段id,我们将相同id的User进行分组,并存放在Map中.(例子不是很恰当,但很能说明问题) public static void main(String[] args) { List<User> list = new ArrayList<>(); list.add(new User(1, 1)); list.add(new User(1, 2)); list.add(new User(2, 1)); list.add(new

  • JAVA JDK8 List分组的实现和用法

    概述 对List进行分组是日常开发中,经常遇到的,在JDK 8中对List按照某个属性分组的代码,超级简单. package test; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util

  • List集合按某个属性或者字段进行分组的操作

    List集合按某个属性或者字段进行分组 List<Object>分组 按照Student对象中的Institution(学院)属性进行分组统计 核心代码 Map<String, List<Student>> collect = stuList.stream().collect(Collectors.groupingBy(Student::getInstitution)); 实现代码示例: public static void main(String[] args) {

  • django实现模型字段动态choice的操作

    需求是根据当前登录用户来显示某个choice字段不同的选择项. 先放现在的实现版本. 1.重写PushRuleForm的__init__方法, 让每次实例化PushRuleForm时,test_mode字段的choices根据用户重新赋值 class PushRuleForm(forms.ModelForm): def __init__(self, *args, **kwargs): if self.request.user.username in Const.TEST_USER_LIST: #

  • java注解之运行时修改字段的注解值操作

    今天遇到需求:导入Excel时候列头会发生变化,客户是大爷要求你改代码, 导入Excel是用easypoi做的,识别表头是用注解@Excel(name = "xxx")通过这个name来匹配 那你表头要动,我这个注解是硬编码 所以就有动态设置这个表头 public class JavaVo{ @Excel(name = "xxx") private String userName; //省略getset方法 } ExcelImportUtil.importExcel

  • MySql Group By对多个字段进行分组的实现方法

    在平时的开发任务中我们经常会用到MYSQL的GROUP BY分组, 用来获取数据表中以分组字段为依据的统计数据.比如有一个学生选课表,表结构如下: Table: Subject_Selection Subject Semester Attendee --------------------------------- ITB001 1 John ITB001 1 Bob ITB001 1 Mickey ITB001 2 Jenny ITB001 2 James MKB114 1 John MKB1

  • js根据json数据中的某一个属性来给数据分组的方法

    如下所示: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <span id ="span" style="width: 50px;height: 200px;"></span> </body> &

  • VUE 实现动态给对象增加属性,并触发视图更新操作示例

    本文实例讲述了VUE 实现动态给对象增加属性,并触发视图更新操作.分享给大家供大家参考,具体如下: 在开发过程中,我们时常会遇到这样一种情况:当vue的data里边声明或者已经赋值过的对象或者数组(数组里边的值是对象)时,向对象中添加新的属性,如果更新此属性的值,是不会更新视图的. 根据官方文档定义:如果在实例创建之后添加新的属性到实例上,它不会触发视图更新. Vue 不允许在已经创建的实例上动态添加新的根级响应式属性 (root-level reactive property).然而它可以使用

  • java用list集合存储学生信息并算出成绩平均值操作

    需求 键盘输入五名学生信息并录入list集合; 输出每个学生的信息,计算并输出这五个学生Java语言成绩的平均值: 计算并输出他们Java语言成绩的最大值和最小值. 思路 用Scanner 键盘输入 用for循环依次录入学生信息 用for循环输出学生信息 用for循环拿出学生成绩并求出成绩平均分 代码 补充知识:java 计算平均值,去除不合理的数据 我就废话不多说了,大家还是直接看代码吧~ package com.ine.tool; import java.util.ArrayList; im

  • vue组件讲解(is属性的用法)模板标签替换操作

    vue中is的属性引入是为了解决dom结构中对放入html的元素有限制的问题,譬如ul里面要接上li的标签,引入is的属性后,你完全可以写成这样 <div class="language-html"> <ul> <li is="row"></li> </ul> </div> 这样会保证dom结构在浏览器的正常渲染,尽量避免在不正确的结构中直接使用组件 <script> Vue.com

  • mysql group by 对多个字段进行分组操作

    在平时的开发任务中我们经常会用到MYSQL的GROUP BY分组, 用来获取数据表中以分组字段为依据的统计数据. 比如有一个学生选课表,表结构如下: Table: Subject_Selection Subject Semester Attendee --------------------------------- ITB001 1 John ITB001 1 Bob ITB001 1 Mickey ITB001 2 Jenny ITB001 2 James MKB114 1 John MKB

随机推荐