要根据对象的 id 去重,可以使用 Java 8 的 Stream API 和 Collectors 工具类来实现。假设有一个包含对象的 List 列表,对象有一个 id 属性,可以按照以下步骤进行去重:

  1. 使用 stream() 方法将列表转换为一个流。
  2. 使用 Collectors.toMap() 方法将流中的对象按照 id 属性作为键进行分组,并使用 Function.identity() 作为值。
  3. 使用 Collectors.collectingAndThen() 方法将分组后的 Map 转换回列表,同时使用 Collectors.toList() 方法去除重复的值。

以下是一个示例代码:

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        List<Person> personList = new ArrayList<>();
        personList.add(new Person(1, 'John'));
        personList.add(new Person(2, 'Alice'));
        personList.add(new Person(1, 'David'));
        personList.add(new Person(3, 'Bob'));
        personList.add(new Person(2, 'Chris'));

        List<Person> distinctList = personList.stream()
                .collect(Collectors.toMap(Person::getId, person -> person, (p1, p2) -> p1))
                .values()
                .stream()
                .collect(Collectors.toList());

        for (Person person : distinctList) {
            System.out.println(person.getId() + ', ' + person.getName());
        }
    }
}

class Person {
    private int id;
    private String name;

    public Person(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }
}

运行上述代码将输出:

1, John
2, Alice
3, Bob

可以看到,重复的对象已经被去除,只保留了唯一的对象。

Java 8 使用 Stream API 和 Collectors 去重列表对象

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

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