Two methods are used to delete repeated elements in ArrayList. Two methods are used to delete repeated elements in arraylist.
There are two ways to delete repeated elements in an ArrayList. In the following program segment, the removeDuplicate method does not maintain the Order, while the removeDuplicateWithOrder method maintains the Order, but it may sacrifice performance.
The removeDuplicate Method:
/** List order not maintained **/ public static void removeDuplicate(ArrayList arlList) { HashSet h = new HashSet(arlList); arlList.clear(); arlList.addAll(h); }
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);}
Remove repeated elements from ArrayList
Public static void main (String [] args ){
List <String> list = new ArrayList <String> ();
List. add ("java ");
List. add ("java ");
List. add ("java ");
List. add ("java ");
List. add ("c ++ ");
Map <String, String> clearMap = new HashMap <String, String> ();
For (String language: list ){
If (! ClearMap. containsKey (language )){
ClearMap. put (language, language );
}
Continue;
}
For (String key: clearMap. keySet ()){
System. out. println (clearMap. get (key) + ",");
}
}
You do not know which duplicate items are excluded, so you are not available in real code.
You can't use 0-list.size () because you cannot delete the list during loop. If you delete the list, an exception is returned.
If you want to use
Use
Iterator <String> iterator = list. iterator ();
While (iterator. hasNext ()){
If ("java". equals (iterator. next ())){
System. out. println (iterator. next ());
Iterator. remove ();
}
}
Use this method
Remove duplicate elements from ArrayList and maintain the order
You can directly use the functions of collections. If it is implemented by yourself, a simple method is to loop through list, put the previous element into another list, and use contains to determine whether the current element is in another list. If it is not in another list, it will continue to be put.