移除ArrayList内重复数据的两个方法

来源:互联网 发布:mac os 如何配置discuz 编辑:程序博客网 时间:2024/05/02 02:17
Expertise: Intermediate
Language: Java
Two Methods to Remove Duplicates in an ArrayList
Here are two methods that allow you to remove duplicates in an ArrayList. removeDuplicate does not maintain the order where as removeDuplicateWithOrder maintains the order with some performance overhead.

1.The removeDuplicate Method:
/** List order not maintained **/
public static void removeDuplicate(ArrayList arlList)

   HashSet h = new HashSet(arlList); 
   arlList.clear(); 
   arlList.addAll(h);
}

2.The removeDuplicateWithOrder Method: 
/** List order maintained **/
public static void removeDuplicateWithOrder(ArrayList arlList)

   Set set = new HashSet(); 
   List newList = new ArrayList(); 
   for (Iterator iter = arlList.iterator(); iter.hasNext(); ) 
   { 
      Object element = iter.next(); 
      if (set.add(element)) newList.add(element); 
   } 
   arlList.clear(); 
   arlList.addAll(newList);
}

Vijayanandraj Amaladoss