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 Answers
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.
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.