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

℡╲_俬逩灬. 提交于 2020-01-17 02:39:46

问题


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()


回答1:


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);

        }



回答2:


Assuming you can change the list to set.

Use the Set Collection instead.

A Set is a Collection that cannot contain duplicate elements.




回答3:


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;
}



回答4:


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.



来源:https://stackoverflow.com/questions/15287842/filter-unique-objects-from-an-arraylist-based-on-property-value-of-the-contained

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!