Dean
Dean

Reputation: 8978

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 through them so i can remove duplicates.
Thanks in Advance,
Dean

Upvotes: 2

Views: 3478

Answers (3)

Joonas Pulakka
Joonas Pulakka

Reputation: 36577

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);

Upvotes: 3

Jonathon Faust
Jonathon Faust

Reputation: 12545

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));

Upvotes: 5

Tassos Bassoukos
Tassos Bassoukos

Reputation: 16142

Off the cuff, will a new ArrayList<Integer>(new HashSet<Integer>(your_list)) work? Oh, don't forget sorting.

Upvotes: 2

Related Questions