• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to remove duplicate elements from arraylist without using hashset

 
upanshu vaid
Ranch Hand
Posts: 83
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


I want to know remove duplicate without using hashset.
kindly suggest.
 
Andrea Binello
Ranch Hand
Posts: 31
Eclipse IDE Java Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
upanshu vaid wrote: I want to know remove duplicate without using hashset.
kindly suggest.

If you don't want to (or can't for didactic reasons) use other collections, apart the original list and the new list, you have to do a linear search every time you are inserting an element in the new list.

You are inserting the first "upanshu" into arrayList2. Does it already exist in arrayList2? No, ok insert it.
You are inserting the second "upanshu" into arrayList2. Does it already exist in arrayList2? Yes, skip it.

You have to do a loop on l and for each element, a loop on arrayList2 to verify if the element is already present.
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That shows how not to insert duplicates.
Removing duplicates is similar: you would have to do a linear search. Maybe use the sublist method. You would also have to decide which elements to remove. Do you remove the first occurrence or subsequent occurrences?
 
Winston Gutkowski
Bartender
Pie
Posts: 10257
59
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
upanshu vaid wrote: I want to know remove duplicate without using hashset.
kindly suggest.

I'm afraid that's a very broad question.

If your question is "how can I prevent duplicates on each addition", then the suggestions you've been given are probably the best. On the other hand, if your question is simply "how can I remove duplicates from my List" then I'd say thatis going to be about as fast as you can get.

However, you need to load ALL your values (including duplicates) into myList first.

HIH

Winston
 
Piet Souris
Rancher
Pie
Posts: 1215
25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hmm... LinkedHashSet is dubious, given that HashSets are not allowed.
So I would advise to use a TreeSet instead.

Another method would be to sort the List, and remove every element that is not
element 0 and is equal to its predecessor.

Greetings,
Piet
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is any predefined Set permissible? Sorting sounds a good idea, but are you allowed to lose the ordering information?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic