本篇文章小编给大家分享一下Java将List中的实体类按照某个字段进行分组并存放至Map中操作代码,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
1、JDK1.8之前:
假设有实体类User,里面有字段id,我们将相同id的User进行分组,并存放在Map中。(例子不是很恰当,但很能说明问题)
public static void main(String[] args) {
Listlist = new ArrayList<>();
list.add(new User(1, 1));
list.add(new User(1, 2));
list.add(new User(2, 1));
list.add(new User(2, 3));
list.add(new User(2, 2));
list.add(new User(3, 1));
Map> map = new HashMap<>();
for(User user : list){
if(map.containsKey(user.getId())){//map中存在此id,将数据存放当前key的map中
map.get(user.getId()).add(user);
}else{//map中不存在,新建key,用来存放数据
ListtmpList = new ArrayList<>();
tmpList.add(user);
map.put(user.getId(), tmpList);
}
}
System.out.println(map.toString());
}
执行结果:
可以看到达到了了我们的目的
2、JDK1.8 新特性实现
Map> map =
list.stream().collect(Collectors.groupingBy(User::getId));
附上
List>>分组
List>> list = new ArrayList<>();
Map>> contractIdMap =
list.stream().collect(Collectors.groupingBy(m -> (Long.parseLong(m.get("contractId").toString()))));
Map>> nameMap =
list.stream().collect(Collectors.groupingBy(m -> (m.get("name").toString())));