0

I have a pojo with variables brand,type and date, I created a Arraylist using this pojo. This arraylist is having duplicates, now i want to remove duplicates from the arraylist by comparing only brand and type of that object. if brand and type are already exists,I need to remove that object from arraylist.

3
  • can you have a code snippet or code sample ? Commented Nov 16, 2016 at 6:26
  • Override equals() & hahscode() and use list1.removeAll(list2) Commented Nov 16, 2016 at 6:28
  • Implement equals() to declare two objects equal if they have the same brand and type (don’t look at date). As a consequence, hashCode() should not look at date either. Commented Nov 16, 2016 at 6:56

2 Answers 2

0

Override equals() and hashCode() of the added class according to your variable, then use LinkedHashSet instead of ArrayList and all your work will be done automatically.

Sign up to request clarification or add additional context in comments.

Comments

0

If you are unable or unwilling to change the equals() method of the POJO, then you will have to use a Map to collect one sample for each distinct brand+type pair.

Here is an example code snippet that does this using a stream:

 list = new ArrayList(list.stream().unordered() .collect(Collectors.toMap( pojo -> new Pair<>(pojo.brand, pojo.type), pojo -> pojo, (original, duplicate) -> original)).values()); 

Alternatively, you could wrap each POJO in a wrapper object which defines equals based only on brand and type, then use the simpler distinct() stream filter, and finally unwrap each result.

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.