list中map集合按key去重

时间:2024-10-29 07:18:10
package com.ztrs.ioms.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> map1 = new HashMap<>();
        map1.put("id", "1");
        map1.put("name", "Alice");

        Map<String, Object> map2 = new HashMap<>();
        map2.put("id", "1"); // 与map1的id相同,视为重复
        map2.put("name", "Bob");

        Map<String, Object> map3 = new HashMap<>();
        map3.put("id", "2");
        map3.put("name", "Charlie");

        list.add(map1);
        list.add(map2);
        list.add(map3);

        List<Map<String, Object>> uniqueList = list.stream()
                .collect(Collectors.toMap(
                        map -> (String) map.get("id"),
                        Function.identity(),
                        (existing, replacement) -> replacement
                )).values().stream().collect(Collectors.toList());

        // 打印结果
        uniqueList.forEach(System.out::println);
    }
}

返回结果:

{name=Bob, id=1}
{name=Charlie, id=2}