删除ArrayList中重复元素
方法一:循环元素删除 (使用的方式FOR循环操作。不建议使用大数据量的转换。。n*n的循环量)
// 删除ArrayList中重复元素
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);
}
方法二:通过HashSet剔除 (hash数组不能产生重复数据的特性,来转换LIST)
// 删除ArrayList中重复元素
HashSet hSet = new HashSet(list);
list.clear();
list.addAll(hSet);
System.out.println(list);
方法三: 删除ArrayList中重复元素,保持顺序
// 删除ArrayList中重复元素,保持顺序
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);
}
________________________________________________
// 项目实践:删除ArrayList中重复元素,保持顺序
public List removeDuplicateWithOrder(List list) {
for (int i = 0; i < list.size(); i++) {
System.out.println("剔除前:"+list.get(i));
}
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);
for (int i = 0; i < list.size(); i++) {
System.out.println("剔除后:"+list.get(i));
}
return list;
}