java ArrayList去重複值
阿新 • • 發佈:2019-01-28
public static List 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);
}
}
return newList;}
===========================
這樣利用set去了重複,又用linked保持住了原順序。
return
new
ArrayList<T>(
new
LinkedHashSet<T>(list));
========
public static List removeDuplicateWithOrder(List list) {
List newList = new ArrayList();
for (Object o : list) {
if (!newList .contains(o)) newList.add(o);
}
return newList;
}
=======
set.addAll(list); List newList = new ArrayList(set.size()); newList.addAll(set); return newList; }
=====
Set<Object> set = new HashSet<Object>(list);