JavaでArrayListの重複要素を削除する方法まとめ

方法1
public static void removeDupElement(List list) {
HashSet h = new HashSet(list);
list.clear();
list.addAll(h);
System.out.println(list);
}

方法2
public static void removeDupElementWithOrder(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( “削除” + list);
}

方法3
public static void removeDupElement(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);
}

Comments are closed.