java 提取list对象重复数据
时间: 2023-08-20 07:05:15 浏览: 92
同样可以使用两个嵌套的循环遍历列表并比较每个对象是否相同。如果相同,则将其添加到另一个列表中,最后返回这个列表。以下是示例代码:
假设我们有一个Person类,其中包含id和name属性:
```
public class Person {
private int id;
private String name;
public Person(int id, String name) {
this.id = id;
this.name = name;
}
// Getters and setters omitted for brevity
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return id == person.id &&
Objects.equals(name, person.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
}
```
然后我们有一个包含Person对象的列表:
```
List<Person> people = Arrays.asList(
new Person(1, "Alice"),
new Person(2, "Bob"),
new Person(3, "Charlie"),
new Person(1, "Alice"),
new Person(4, "David"),
new Person(3, "Charlie")
);
```
现在我们可以使用以下代码来提取重复的Person对象:
```
List<Person> duplicates = new ArrayList<>();
for (int i = 0; i < people.size(); i++) {
for (int j = i + 1; j < people.size(); j++) {
if (people.get(i).equals(people.get(j))) {
if (!duplicates.contains(people.get(i))) {
duplicates.add(people.get(i));
}
}
}
}
System.out.println("Duplicates: " + duplicates);
```
输出结果为:`Duplicates: [Person{id=1, name='Alice'}, Person{id=3, name='Charlie'}]`。
阅读全文