要根据 map 属性去重,可以使用 Java 8 中的 Stream API 来实现。以下是一个示例代码:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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', 'John');
        map1.put('age', 25);
        
        Map<String, Object> map2 = new HashMap<>();
        map2.put('id', 2);
        map2.put('name', 'Jane');
        map2.put('age', 30);
        
        Map<String, Object> map3 = new HashMap<>();
        map3.put('id', 1);
        map3.put('name', 'John');
        map3.put('age', 25);
        
        list.add(map1);
        list.add(map2);
        list.add(map3);
        
        List<Map<String, Object>> distinctList = list.stream()
                .collect(Collectors.toMap(
                        map -> map.get('id') + '-' + map.get('name') + '-' + map.get('age'), 
                        map -> map, 
                        (existing, replacement) -> existing))
                .values()
                .stream()
                .collect(Collectors.toList());
        
        System.out.println(distinctList);
    }
}

在上述示例中,我们使用 Collectors.toMap() 方法将 List<Map<String, Object>> 转换为 Map<String, Map<String, Object>>,其中 key 是根据 map 属性拼接而成的字符串,value 是原始的 map 对象。参数 existingreplacement 用于处理重复的 key,我们选择保留已存在的 map 对象。最后,我们使用 values() 方法获取去重后的 map 对象集合,并使用 Collectors.toList() 方法将其转换为 List<Map<String, Object>>

输出结果为:

[{id=1, name=John, age=25}, {id=2, name=Jane, age=30}]
Java List<Map<String, Object>> 去重:使用 Stream API 实现

原文地址: https://www.cveoy.top/t/topic/qhFD 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录