stream流list去重多字段
时间: 2023-10-09 16:17:43 浏览: 49
如果要对一个 `List` 中的对象进行去重,可以使用 Java 8 中的 `stream` 和 `distinct` 方法。假设我们有一个 `Person` 类,其中包含 `name` 和 `age` 两个字段,我们要对一个 `List<Person>` 进行去重,可以按照以下方法进行。
```java
List<Person> personList = new ArrayList<>();
personList.add(new Person("Alice", 20));
personList.add(new Person("Bob", 30));
personList.add(new Person("Alice", 20));
personList.add(new Person("Charlie", 40));
List<Person> distinctPersonList = personList.stream()
.distinct()
.collect(Collectors.toList());
```
这里我们使用 `distinct` 方法对 `stream` 中的元素进行去重操作,`distinct` 方法默认使用对象的 `equals` 方法进行判断是否相等,如果要自定义对象的相等规则,可以重写 `equals` 方法和 `hashCode` 方法。
我们可以在 `Person` 类中重写 `equals` 方法和 `hashCode` 方法,按照 `name` 和 `age` 两个字段进行判断是否相等。
```java
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return age == person.age &&
Objects.equals(name, person.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}
```
使用重写后的 `equals` 方法和 `hashCode` 方法,我们可以对 `Person` 对象进行按照 `name` 和 `age` 两个字段进行去重。
```java
List<Person> distinctPersonList = personList.stream()
.distinct()
.collect(Collectors.toList());
```