对象list排序、分组、去重处理

对象list排序

  • 根据list中每个对象的单个属性进行排序
//根据Dict对象的sort字段降序排序
dictList.sort(Comparator.comparing(Dict::getSort).reversed());
//根据Dict对象的sort字段升序排序
dictList.sort(Comparator.comparing(Dict::getSort));
  • 根据list中每个对象的多个属性进行排序
// DBFieldInfoTemp对象中,先根据TableName字段排序,	再根据level字段排序
Comparator<DBFieldInfoTemp> byTableName = Comparator.comparing(DBFieldInfoTemp::getTableName);
Comparator<DBFieldInfoTemp> byLevel = Comparator.comparing(DBFieldInfoTemp::getLevel, new Comparator<String>() {
                        @Override
                        public int compare(String o1, String o2) {
                            if (o1 != null && o2 != null) {
                                return o2.compareTo(o1);
                            } else if (o1 == null && o2 == null) {
                                return 0;
                            } else {
                                return o1 == null ? 1 : -1;
                            }
                        }
                    });
alertFields = JSONArray.parseArray(dbProcessInfo.getAlertFields(), DBFieldInfoTemp.class);
Collections.sort(alertFields, byTableName.thenComparing(byLevel));

对象list分组

  • 根据list中每个对象的单个属性进行分组
Map<String, List<ClassEntity>> collect = classEntities.stream().collect(Collectors.groupingBy(ClassEntity::getGrade));
  • 根据list中每个对象的多个属性进行分组
// 根据员工电话+场所id+员工身份证号分组,取申报时间最新一条
 Map<String, List<MeoEpidemicEmpDeclare>> mapGroup = epidemicEmpDeclareList.stream().collect(Collectors.groupingBy(v -> v.getEmpPhone() + v.getPlaceId() + v.getEmpIdCard()));
  • 根据list中每个对象的单个属性进行分组并进行组内排序
//对于list 按照 versionCount 字段分组,并且降序存储到treeMap中,,实现分组的数据是有序的。
TreeMap<Integer, List<StudenData>> listTreeMap = studentList.parallelStream().collect(Collectors.groupingBy( StudentData::getVerSionCount,
                        () -> new TreeMap<>((Comparator.reverseOrder())),
                        Collectors.toList()));

对象list去重

  • 根据list中每个对象的单个属性进行去重
List<Player> newList = playerList.stream().collect(Collectors.collectingAndThen(
                  Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Player::getName))),
                  ArrayList::new));
  • 根据list中每个对象的多个属性进行去重
List<ClassEntity> distinctClass = classEntities.stream().collect(
		Collectors.collectingAndThen(
			Collectors.toCollection(
				() -> new TreeSet<>(
					Comparator.comparing(
						o -> o.getProfessionId() + ";" + o.getGrade()))), ArrayList::new));
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值