import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class ObjectArrayDeduplicationWithStream {
static class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = 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 && name.equals(person.name);
}
@Override
public int hashCode() {
int result = name.hashCode();
result = 31 * result + age;
return result;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
public static void main(String[] args) {
Person[] persons = {new Person("Alice", 20), new Person("Bob", 25), new Person("Alice", 20)};
List<Person> uniquePersons = Arrays.stream(persons)
.distinct()
.collect(Collectors.toList());
for (Person person : uniquePersons) {
System.out.println(person);
}
}
}
07-02
3283
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
04-26
212
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
04-04