如果对象顺序无关紧要
如果顺序不重要,可以将列表的元素放入Set:
Set<MyObject> mySet = new HashSet<MyObject>(yourList);
重复的将被自动删除。
如果对象顺序很重要
如果排序很重要,那么您可以手动检查重复项,例如使用这个 sn-p:
// Copy the list.
ArrayList<String> newList = (ArrayList<String>) list.clone();
// Iterate
for (int i = 0; i < list.size(); i++) {
for (int j = list.size() - 1; j >= i; j--) {
// If i is j, then it's the same object and don't need to be compared.
if (i == j) {
continue;
}
// If the compared objects are equal, remove them from the copy and break
// to the next loop
if (list.get(i).equals(list.get(j))) {
newList.remove(list.get(i));
break;
}
System.out.println("" + i + "," + j + ": " + list.get(i) + "-" + list.get(j));
}
}
这将删除所有重复项,将最后一个重复值保留为原始条目。此外,它只会检查每个组合一次。
使用 Java 8
Java Streams 让它更加优雅:
List<Integer> newList = oldList.stream()
.distinct()
.collect(Collectors.toList());
如果您需要根据自己的定义考虑两个对象相等,您可以执行以下操作:
public static <T, U> Predicate<T> distinctByProperty(Function<? super T, ?> propertyExtractor) {
Set<Object> seen = ConcurrentHashMap.newKeySet();
return t -> seen.add(propertyExtractor.apply(t));
}
(Stuart Marks)
然后你可以这样做:
List<MyObject> newList = oldList.stream()
.filter(distinctByProperty(t -> {
// Your custom property to use when determining whether two objects
// are equal. For example, consider two object equal if their name
// starts with the same character.
return t.getName().charAt(0);
}))
.collect(Collectors.toList());
此外
Iterator(通常在 for-each 循环中使用)在数组中循环时不能修改列表。这将抛出一个ConcurrentModificationException。如果您使用 for 循环对其进行循环,则可以修改该数组。然后你必须控制迭代器的位置(在删除条目时递减它)。