Java对List<Map>根据key进行排序、去重、分组

时间:2025-04-04 07:44:01
public static void mapListExample() { Map<String, Object> mapData = new HashMap<String, Object>() {{ put("name", "xiaoyi"); put("age", "28"); put("sex", "male"); }}; Map<String, Object> mapData2 = new HashMap<String, Object>() {{ put("name", "xiaoer"); put("age", "22"); put("sex", "male"); }}; Map<String, Object> mapData3 = new HashMap<String, Object>() {{ put("name", "xiaosan"); put("age", "23"); put("sex", "female"); }}; Map<String, Object> mapData4 = new HashMap<String, Object>() {{ put("name", "xiaoliu"); put("age", "20"); put("sex", "male"); }}; Map<String, Object> mapData5 = new HashMap<String, Object>() {{ put("name", "yanzi"); put("age", "20"); put("sex", "female"); }}; List<Map<String, Object>> mapList = Arrays.asList(mapData, mapData2, mapData3, mapData4, mapData5); Collections.sort(mapList, new Comparator<Map<String, Object>>() { @Override public int compare(Map<String, Object> o1, Map<String, Object> o2) { return o1.get("name").toString().compareTo(o2.get("name").toString()); } }); System.out.println(mapList); mapList.sort(Comparator.comparing(item->item.get("name").toString())); mapList.sort(Comparator.comparingInt(item->Integer.valueOf(item.get("age").toString()))); System.out.println("根据年龄进行排序======>"+mapList); //List<Map> 按某个key去重(重要记忆) ArrayList<Map<String, Object>> mapArrayList = mapList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(item -> item.get("age").toString()))), ArrayList::new)); System.out.println("按某个key去重======>"+mapArrayList); System.out.println("========================================================="); //List<Map> groupBy按某个key分组(重要记忆) //Collector<Map<String, Object>, ?, Map<Object, List<Map<String, Object>>>> age = (item -> ("age")); Map<String, List<Map<String, Object>>> groupMap = mapList.stream().collect(Collectors.groupingBy(item -> item.get("age").toString())); System.out.println("groupBy按某个key分组====>"+groupMap); List<Map<String, Object>> collectList = new ArrayList<>(); for (Map.Entry<String,List<Map<String, Object>>> entry : groupMap.entrySet()){ List<Map<String, Object>> value = entry.getValue(); Map<String, Object> oneMap = value.get(0); Integer ageAdd = 0; if (value.size() > 0){ for (Map<String, Object> objectMap : value) { ageAdd += Integer.valueOf(objectMap.get("age").toString()); } oneMap.put("age",ageAdd); collectList.add(oneMap); }else{ collectList.add(oneMap); } } System.out.println("相同key的年龄相加=======>"+collectList); }