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 User(2, 3));
list.add(new User(2, 2));
list.add(new User(3, 1));
Map<Integer, List<User>> 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,用来存放数据
List<User> tmpList = new ArrayList<>();
tmpList.add(user);
map.put(user.getId(), tmpList);
}
}
System.out.println(map.toString());
}
执行结果:
可以看到达到了了我们的目的
2、JDK1.8 新特性实现
Map<Integer, List<User>> map = list.stream().collect(Collectors.groupingBy(User::getId));
附上
List<Map<String, Object>>>分组
List<Map<String, Object>>> list = new ArrayList<>();
Map<Long, List<Map<String, Object>>> contractIdMap =
list.stream().collect(Collectors.groupingBy(m -> (Long.parseLong(m.get("contractId").toString()))));
Map<Long, List<Map<String, Object>>> nameMap =
list.stream().collect(Collectors.groupingBy(m -> (m.get("name").toString())));
补充知识:java中对list的数据按照某个属性进行分组,拆分成多个list
我就废话不多说了,大家还是直接看代码吧~
/**
* 按照List<Map<String,Object>>里面map的某个value重新封装成多个不同的list, 原始数据类型List<Map
* <String,Object>>, 转换后数据类型Map<String,List<Map<String,Object>>>
*
* @param list
* @param oneMapKey
* @return
*/
private static Map<String, Object> change(List<Map<String, Object>> list, String oneMapKey) {
Map<String, Object> resultMap = new HashMap<String, Object>();
Set setTmp = new HashSet();
for (Map<String, Object> tmp : list) {
setTmp.add(tmp.get(oneMapKey));
}
Iterator it = setTmp.iterator();
while (it.hasNext()) {
String oneSetTmpStr = (String) it.next();
List<Map<String, Object>> oneSetTmpList = new ArrayList<Map<String, Object>>();
for (Map<String, Object> tmp : list) {
String oneMapValueStr = (String) tmp.get(oneMapKey);
if (oneMapValueStr.equals(oneSetTmpStr)) {
oneSetTmpList.add(tmp);
}
}
resultMap.put(oneSetTmpStr, oneSetTmpList);
}
return resultMap;
}
以上这篇Java 将List中的实体类按照某个字段进行分组并存放至Map中操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持社区。 |