注意:自定义对象需要重写equals()和 hashcode()
1.方法一
public static void removeDuplicate(List list) {
for (int i = 0; i < list.size() - 1; i++) {
for (int j = list.size() - 1; j > i; j--) {
if (list.get(j).equals(list.get(i))) {
list.remove(j);
}
}
}
System.out.println(list);
}
2.方法二
public static void removeDuplicate1(List list) {
HashSet h = new HashSet(list);
list.clear();
list.addAll(h);
System.out.println(list);
}
3.方法三
public static void removeDuplicateWithOrder(List list) {
Set set = new HashSet();
List newList = new ArrayList();
for (Iterator iter = list.iterator(); iter.hasNext();) {
Object element = iter.next();
if (set.add(element))
newList.add(element);
}
list.clear();
list.addAll(newList);
System.out.println(" remove duplicate " + list);
}
4.方法四
public static void removeDuplicateWithOrder(List list) {
List collect = list.stream().distinct().collect(Collectors.toList());
System.out.println(collect);
}