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.
Asked
Active
Viewed 421 times
0
-
can you have a code snippet or code sample ? – msagala25 Nov 16 '16 at 06:26
-
Override equals() & hahscode() and use list1.removeAll(list2) – Vasu Nov 16 '16 at 06: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. – Ole V.V. Nov 16 '16 at 06:56
2 Answers
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.

jkdev
- 11,360
- 15
- 54
- 77

mayank agrawal
- 628
- 5
- 20
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.

Patrick Parker
- 4,863
- 4
- 19
- 51