JAVA對map進行分組
阿新 • • 發佈:2019-04-21
public static Map<String, List<Map<String, Object>>> transition(List<Map<String, Object>> list){
Map<String, List<Map<String, Object>>> map = new HashMap<>();
// 分組
for(Map<String, Object> temp : list) {
// 獲取Map的每一對值
Iterator<Map.Entry<String, Object>> iterator = temp.entrySet().iterator();
while (iterator.hasNext()) {
List<Map<String, Object>> listAndMap = new ArrayList<>();
// 獲取到每一個實體
Map.Entry<String, Object> entity = iterator.next();
if (map.containsKey(entity.getKey())) {
// 獲取原來存在的資料
List<Map<String, Object>> lm = map.get(entity.getKey());
lm.add(new HashMap<String, Object>() {{
put(entity.getKey(), entity.getValue());
}});
Collections.sort(lm, (param1, param2) ->
(param2.get(entity.getKey()).toString().compareTo(param1.get(entity.getKey()).toString()))
);
map.replace(entity.getKey(), lm);
} else {
listAndMap.add(new HashMap<String, Object>() {{
put(entity.getKey(), entity.getValue());
}});
map.put(entity.getKey(), listAndMap);
}
}
}
return