我有一个List
的人,我想找到重复的条目,包括除id
之外的所有字段。所以使用 equals()
-方法(因此List.contains()
),因为他们考虑了id
。
public class Person {
private String firstname, lastname;
private int age;
private long id;
}
修改 equals()
和 hashCode()
-方法以忽略id
字段不是一个选项,因为代码的其他部分依赖于此字段。
如果我想忽略id
字段,Java 中整理重复项的最有效方法是什么?
构建一个Comparator<Person>
来实现自然键排序,然后使用基于二进制搜索的重复数据删除。 TreeSet
会给你这种开箱即用的能力。
请注意,Comparator<T>.compare(a, b)
必须满足通常的反对称性、传递性、一致性和反身性要求,否则二叉搜索排序将失败。您还应该使其能够识别空值(例如,如果一个、另一个或两个的名字字段为空)。
Person 类的简单自然键比较器如下所示(它是一个静态成员类,因为您尚未显示每个字段都有访问器)。
public class Person {
public static class NkComparator implements Comparator<Person>
{
public int compare(Person p1, Person p2)
{
if (p1 == null || p2 == null) throw new NullPointerException();
if (p1 == p2) return 0;
int i = nullSafeCompareTo(p1.firstname, p2.firstname);
if (i != 0) return i;
i = nullSafeCompareTo(p1.lastname, p2.lastname);
if (i != 0) return i;
return p1.age - p2.age;
}
private static int nullSafeCompareTo(String s1, String s2)
{
return (s1 == null)
? (s2 == null) ? 0 : -1
: (s2 == null) ? 1 : s1.compareTo(s2);
}
}
private String firstname, lastname;
private int age;
private long id;
}
然后,您可以使用它来生成唯一列表。使用 add
方法,该方法返回 true
当且仅当元素在集合中不存在时:
List<Person> newList = new ArrayList<Person>();
TreeSet<Person> nkIndex = new TreeSet<Person>(new Person.NkComparator());
for (Person p : originalList)
if (nkIndex.add(p)) newList.add(p); // to generate a unique list
或者交换此行的最后一行以输出重复项
if (nkIndex.add(p)) newList.add(p);
无论您做什么,在枚举原始列表时都不要在原始列表中使用 remove
,这就是这些方法将您的唯一元素添加到新列表中的原因。
如果您只是对唯一列表感兴趣,并希望使用尽可能少的行:
TreeSet<Person> set = new TreeSet<Person>(new Person.NkComparator());
set.addAll(originalList);
List<Person> newList = new ArrayList<Person>(set);
@LuiggiMendoza评论中所建议的:
您可以创建一个自定义 Comparator
类,该类比较两个Person
对象的相等性,忽略它们的 id。
class PersonComparator implements Comparator<Person> {
// wraps the compareTo method to compare two Strings but also accounts for NPE
int compareStrings(String a, String b) {
if(a == b) { // both strings are the same string or are null
return 0;
} else if(a == null) { // first string is null, result is negative
return -1;
} else if(b == null){ // second string is null, result is positive
return 1;
} else { // no strings are null, return the result of compareTo
return a.compareTo(b);
}
}
@Override
public int compare(Person p1, Person p2) {
// comparisons on Person objects themselves
if(p1 == p2) { // Person 1 and Person 2 are the same Person object
return 0;
}
if(p1 == null && p2 != null) { // Person 1 is null and Person 2 is not, result is negative
return -1;
}
if(p1 != null && p2 == null) { // Person 1 is not null and Person 2 is, result is positive
return 1;
}
int result = 0;
// comparisons on the attributes of the Persons objects
result = compareStrings(p1.firstname, p2.firstname);
if(result != 0) { // Persons differ in first names, we can return the result
return result;
}
result = compareStrings(p1.lastname, p2.lastname);
if(result != 0) { // Persons differ in last names, we can return the result
return result;
}
return Integer.compare(p1.age, p2.age); // if both first name and last names are equal, the comparison difference is in their age
}
}
现在,您可以将TreeSet
结构与此自定义Comparator
一起使用,例如,创建一个消除重复值的简单方法。
List<Person> getListWithoutDups(List<Person> list) {
List<Person> newList = new ArrayList<Person>();
TreeSet<Person> set = new TreeSet<Person>(new PersonComparator()); // use custom Comparator here
// foreach Person in the list
for(Person person : list) {
// if the person isn't already in the set (meaning it's not a duplicate)
// add it to the set and the new list
if(!set.contains(person)) {
set.add(person);
newList.add(person);
}
// otherwise it's a duplicate so we don't do anything
}
return newList;
}
TreeSet
中的contains
操作,如文档所述,"提供有保证的log(n)时间成本"。
我上面建议的方法需要O(n*log(n))
时间,因为我们要对每个列表元素执行contains
操作,但它也使用O(n)
空间来创建新列表和TreeSet
。
如果您的列表非常大(空间非常重要),但您的处理速度不是问题,那么您可以删除找到的每个重复项,而不是将每个非重复项添加到列表中:
List<Person> getListWithoutDups(List<Person> list) {
TreeSet<Person> set = new TreeSet<Person>(new PersonComparator()); // use custom Comparator here
Person person;
// for every Person in the list
for(int i = 0; i < list.size(); i++) {
person = list.get(i);
// if the person is already in the set (meaning it is a duplicate)
// remove it from the list
if(set.contains(person) {
list.remove(i);
i--; // make sure to accommodate for the list shifting after removal
}
// otherwise add it to the set of non-duplicates
else {
set.add(person);
}
}
return list;
}
由于列表上的每个remove
操作都需要O(n)
时间(因为每次删除元素时列表都会移动),并且每个contains
操作都需要log(n)
时间,因此此方法将及时O(n^2 log(n))
。
但是,空间复杂度将减半,因为我们只创建TreeSet
而不是第二个列表。
我建议不要使用Comparator
来执行此操作。基于其他字段编写法律compare()
方法是相当困难的。
我认为更好的解决方案是创建一个类PersonWithoutId
如下所示:
public PersonWithoutId {
private String firstname, lastname;
private int age;
// no id field
public PersonWithoutId(Person original) { /* copy fields from Person */ }
@Overrides public boolean equals() { /* compare these 3 fields */ }
@Overrides public int hashCode() { /* hash these 3 fields */ }
}
然后,给定一个名为 people
的List<Person>
,您可以执行以下操作:
Set<PersonWithoutId> set = new HashSet<>();
for (Iterator<Person> i = people.iterator(); i.hasNext();)
if (!set.add(new PersonWithoutId(i.next())))
i.remove();
编辑
正如其他人在评论中指出的那样,此解决方案并不理想,因为它为垃圾收集器创建了要处理的对象负载。但是这个解决方案比使用Comparator
和TreeSet
的解决方案要快得多。保持Set
井然有序需要时间,与原始问题无关。我在 1,000,000 个Person
构建实例的 List
上对此进行了测试
new Person(
"" + rand.nextInt(500), // firstname
"" + rand.nextInt(500), // lastname
rand.nextInt(100), // age
rand.nextLong()) // id
并发现该解决方案的速度大约是使用TreeSet
的解决方案的两倍。(诚然,我使用了System.nanoTime()
而不是适当的基准测试)。
那么,如何在不创建大量不必要的对象的情况下有效地做到这一点呢?Java并不容易。一种方法是用Person
编写两个新方法
boolean equalsIgnoringId(Person other) { ... }
int hashCodeIgnoringId() { ... }
然后编写Set<Person>
的自定义实现,其中基本上剪切和粘贴HashSet
的代码,除了用equalsIgnoringId()
和hashCodeIgnoringId()
替换equals()
和hashCode()
。
以我的拙见,您可以创建一个使用 Comparator
的TreeSet
,但不能创建一个使用 equals
/hashCode
自定义版本的HashSet
,这是该语言中的一个严重缺陷。
Java HashMap
使用<K,V>
对。 Map<K,V> map = new HashMap<K,V>()
.此外,可以使用某种形式的比较器实现。如果您使用 containsKey 或 containsValue 方法检查并发现您已经有一些东西(即您正在尝试添加重复项,请将它们保留在原始列表中。否则,请弹出它们。这样,您最终将得到一个列表,其中包含原始列表中重复的元素。TreeSet<,>将是另一种选择,但我还没有使用它,所以无法提供建议。