2

In my program I have an array list containing product objects in it. I want to remove duplicated product objects from it. Is there any efficient way other than looping over each element and compare them.

1

7 Answers 7

10

just add all element into set. it wont allow duplicate values

   List<Product> list=new ArrayList<>();
   Set<Product> set=new HashSet<>();
   set.addAll(list);
Sign up to request clarification or add additional context in comments.

Comments

5

Just pass your list Collection to Hashset constructor and Get it back.

Then that one liner will be,

list = new ArrayList<E>(new HashSet<E>(list));

Comments

5

You can just put element into Set. Set keep unique values only.

   List<String> list=new ArrayList<>();
   Set<String> set=new HashSet<>();
   set.addAll(list); // now you have unique value set

If you want to final result as unique value List just you need to get this Set as List

   List<String> uniqueValList=new ArrayList<>(set);

Comments

2

You can use a Set but you will loose the original order of your list.

What you can do to keep the order is:

Set<E> copied = new HashSet<>();
List<E> res = new ArrayList<>();
for(E e : originalList) {
    if(!copied.contains(e)) {
        res.add(e);
    }
    copied.add(e);
}

Comments

1

Use Set instead of list it will remove duplicates

Comments

1

Try to use Set instead of List. Set wont allow duplicate values.

Comments

0

The advice above to use Set is good - but if you need to keep the order just use a LinkedHashSet http://docs.oracle.com/javase/7/docs/api/java/util/LinkedHashSet.html

List<String> list = ...
Set<String> set = new LinkedHashSet<>(list);
list.clear();
list.addAll(set);

That will preserve order and remove all duplicates.

The result will be case sensitive though in the case of strings.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.