ArrayList does not have a packaged deduplication method. For example, for an ArrayList of [2, 5, 2, 3, 2, 4], I want to remove the duplicate elements in it.
I don’t want to make the statement so long, nor do I want to use the for loop method to deduplicate it. Then I can first consider converting the ArrayList into a temporary HashSet, and then converting the temporary HashSet back to the ArrayList, because the elements in the HashSet are not repeatable! As for what ArrayList and HashSet are, it has been explained very clearly in "Detailed Explanation of Collections Class in Java", so I will not repeat it here.
You can write this way:
HashSet<Integer> hashset_temp = new HashSet<Integer>(arraylist);
arraylist = new ArrayList<Integer>(hashset_temp);
It can also be written more concisely, and even the temporary hashset_temp variable is not needed:
arraylist = new ArrayList<Integer>(new HashSet<Integer>(arraylist));
After that, the element of ArrayList becomes [2, 3, 4, 5]
Next, I will share with you two ways to remove heavy loads from ArrayList
//Repeat method one
private ArrayList RemoveDuplicateNum(ArrayList list) { list.Sort(); for (int i = 0; i < list.Count - 1; i++) { if (list[i].Equals(list[i + 1])) { list.RemoveAt(i);//Deduplicate item i--; } } return list; } //Repeat method two
private ArrayList RemoveSame(ArrayList list) { //The sentence written above is redundant, this is the final for (int i = 0; i < list.Count - 1; i++) { for (int j = i + 1; j < list.Count; j++) { if (list[i].Equals(list[j])) { list.RemoveAt(j); j--; } } } return list; }The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.