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.

2 Answers2

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