Saturday 10 June 2017

Remove duplicate user defined objects from an ArrayList

To remove duplicate user defined objects we need to override hashCode() and equals() methods and update the comparison logic accordingly.

I had a scenario where I had a list of objects, I need to remove duplicates from the list. I have overrided hashcode() and equals() method. When the duplicate object is encountered, the hashcode value will be same, then equals method is executed. If both objects are equal then it returns true and object will not be added to HashSet.

package com.kishore.samples;

import java.util.ArrayList;
import java.util.HashSet;

public class RemoveDuplicates {

    public static void main(String a[]) {

        ArrayList<Price> listOfBlogs = new ArrayList<>();
        listOfBlogs.add(new Price("aaa", 20));
        listOfBlogs.add(new Price("22", 40));
        listOfBlogs.add(new Price("333", 30));
        listOfBlogs.add(new Price("aaa", 200));

        HashSet<Price> set = new HashSet(listOfBlogs);
        for (Price pr : set) {
            System.out.println(pr);
        }

    }
}

class Price {

    private String item;
    private int price;

    public Price(String itm, int pr) {
        this.item = itm;
        this.price = pr;
    }

    public int hashCode() {
        System.out.println("In hashcode");
        int hashcode = 0;

        hashcode = item.hashCode();
        hashcode += item.hashCode();
        System.out.println("hash code value for " + item + " is " + hashcode);
        return hashcode;
    }

    public boolean equals(Object obj) {
        System.out.println("In equals");
        if (obj instanceof Price) {
            Price pp = (Price) obj;
            return (pp.item.equals(this.item));
        } else {
            return false;
        }
    }

    public String getItem() {
        return item;
    }

    public void setItem(String item) {
        this.item = item;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public String toString() {
        return "item: " + item + "  price: " + price;
    }
}

Output:

In hashcode
hash code value for aaa is 192642
In hashcode
hash code value for 22 is 3200
In hashcode
hash code value for 333 is 101286
In hashcode
hash code value for aaa is 192642
In equals
item: aaa  price: 20
item: 22  price: 40
item: 333  price: 30

No comments :

Post a Comment