JAVA使用stream流对对象集合包括(List<JsonObject>)根据某个字段去重

 

 

 userList = userList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(()->new TreeSet<>(Comparator.comparing(User::getCity))), ArrayList::new));

 

User::getCity 对象要去重的这段,这里表示根据城市属性进行去重


List<JsonObject> 根据某几个字段去重 AI的 记录下
import com.alibaba.fastjson.JSONObject;
import java.util.*;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        List<JSONObject> list = new ArrayList<>();
        JSONObject o1 = new JSONObject();
        o1.put("id", 1);
        o1.put("name", "Alice");
        o1.put("age", 20);

        JSONObject o2 = new JSONObject();
        o2.put("id", 1);
        o2.put("name", "Alice"); // 重复
        o2.put("age", 25);

        JSONObject o3 = new JSONObject();
        o3.put("id", 2);
        o3.put("name", "Bob");
        o3.put("age", 30);

        list.add(o1);
        list.add(o2);
        list.add(o3);

        // 按 id + name 去重
        List<JSONObject> unique = list.stream()
            .collect(Collectors.collectingAndThen(
                Collectors.toMap(
                    obj -> Arrays.asList(obj.get("id"), obj.get("name")),
                    obj -> obj,
                    (existing, replacement) -> existing,
                    LinkedHashMap::new
                ),
                map -> new ArrayList<>(map.values())
            ));

        unique.forEach(System.out::println);
        // 输出 o1 和 o3(o2 被去重)
    }
}

 

posted @ 2023-04-14 09:57  yvioo  阅读(1571)  评论(0)    收藏  举报