Pawan
Pawan

Reputation: 32331

Is it possible to remove duplicates from a List containing elements of a custom type?

This is my code

package com.dto;

public class OtherBrands {

    private String otherbrandsname ;
    public String getOtherbrandsname() {
        return otherbrandsname;
    }
    public void setOtherbrandsname(String otherbrandsname) {
        this.otherbrandsname = otherbrandsname;
    }
    public String getDealerBrandQty() {
        return dealerBrandQty;
    }
    public void setDealerBrandQty(String dealerBrandQty) {
        this.dealerBrandQty = dealerBrandQty;
    }
    private String dealerBrandQty ;

}

import java.util.ArrayList;
import java.util.List;
import com.dto.OtherBrands;

public class Test {
    public static void main(String args[])
    {
        List < OtherBrands > otherBrandsList = new ArrayList < OtherBrands > ();
        for (int k = 0; k < 3; k++) {
            OtherBrands otherbrands = new OtherBrands();
            String otherbrandsname = "Test";
            String dealerBrandQty = "2";
            otherbrands.setOtherbrandsname(otherbrandsname);
            otherbrands.setDealerBrandQty(dealerBrandQty);
            otherBrandsList.add(otherbrands);
        }

        for(int i=0;i<otherBrandsList.size();i++)
        {
            System.out.println(otherBrandsList.get(i).getOtherbrandsname()+"\t"+otherBrandsList.get(i).getDealerBrandQty());

        }
    }
}

When I run this program, the result is :

Test    2
Test    2
Test    2

If the key and value are the same, it should be treated as duplicate

Is it possible to remove the duplicates from the list?

Upvotes: 1

Views: 119

Answers (2)

SME_Dev
SME_Dev

Reputation: 1890

You should use a HashSet instead of an ArrayList, because it guarantees removal of duplicate items. It only requires you to implement the hashCode() and equals() methods in the OtherBrands class.

As a tip, if you use Eclipse: you can generate both methods with the editor menu feature ' Source/Generate HashCode and Equals '. Then select all the attributes, that define the identity of an OtherBrands item (name, quantity).

Upvotes: 1

Eran
Eran

Reputation: 393866

First of all, if you want to avoid duplicates, use a HashSet instead of a List.

Second of all, you have to override hashCode and equals in order for the HashSet to know which elements you consider to be equal to each other.

public class OtherBrands {

    @Override
    public boolean equals (Object other)
    {
        if (!(other instanceof OtherBrands))
            return false;
        OtherBrands ob = (OtherBrands) other;
        // add some checks here to handle any of the properties being null
        return otherbrandsname.equals(ob.otherbrandsname) &&
               dealerBrandQty.equals(ob.dealerBrandQty);
    }

    @Override
    public int hashCode ()
    {
        return Arrays.hashCode(new String[]{dealerBrandQty,otherbrandsname});
    }
}

Upvotes: 4

Related Questions