How to remove duplicate entries in an ArrayList
I have an ArrayList<Integer>
that is full of years that it pulls from my database i want to know how it is possible to loop thr开发者_JAVA百科ough them so i can remove duplicates.
Use a Set
instead of a List
if duplicates shouldn't exist.
You can either use a Set
where you're currently using your List
, or you can use the Set
to remove duplicate elements.
Set<Integer> years = new HashSet<Integer>(myOldArrayList);
Or you could transform from one collection to another. I'm not sure what performance implications there are:
ArrayList<Integer> years = // populate from database
years = new ArrayList<Integer>(new HashSet<Integer>(years));
If the order doesn't matter, just make a Set
out of them, and then back to list again if needed:
Set<Integer> set = new HashSet<Integer>(yourList);
ArrayList<Integer> list = new ArrayList<Integer>(set);
Off the cuff, will a new ArrayList<Integer>(new HashSet<Integer>(your_list))
work? Oh, don't forget sorting.
精彩评论