简体   繁体   中英

Filter unique objects from an ArrayList based on property value of the contained object

How will I filter unique object from an arraylist.

List<LabelValue> uniqueCityListBasedState = new ArrayList<LabelValue>();
for (LabelValue city : cityListBasedState) {
    if (!uniqueCityListBasedState.contains(city)) {
        uniqueCityListBasedState.add(city);
    }
}

This is my code. But the problem is that I need to filter not on the object but on the value of a property inside that object. In this case, I need to exclude the objects that has the name.

That is city.getName()

List<LabelValue> uniqueCityListBasedState = new ArrayList<LabelValue>();
        uniqueCityListBasedState.add(cityListBasedState.get(0));
        for (LabelValue city : cityListBasedState) {
            boolean flag = false;
            for (LabelValue cityUnique : uniqueCityListBasedState) {    
                if (cityUnique.getName().equals(city.getName())) {
                    flag = true;                    
                }
            }
            if(!flag)
                uniqueCityListBasedState.add(city);

        }

Assuming you can change the list to set.

Use the Set Collection instead.

A Set is a Collection that cannot contain duplicate elements.

Overwrite the equals() and hashCode() methods of LabelValue ( hashCode is not a must in this case):

String name;

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((name == null) ? 0 : name.hashCode());
    return result;
}

@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    LabelValueother = (LabelValue) obj;
    if (name == null) {
        if (other.name != null)
            return false;
    } else if (!name.equals(other.name))
        return false;
    return true;
}

Here is one way to solve it.

You should override the equals() method and hashCode() of LabelValue.

And the equals() method should use the name property and so should the hashCode() method.

Then your code will work.

PS. Im assuming that your LabelValue objects can be distinguished with just the name property, which is what you seem to need anyway based on your question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM