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

How can I filter a 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 the object, but the value of the property inside this object. In this case, I need to exclude objects with a name.

it city.getName()

0
source share
4 answers
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);

        }
+6
source

Assuming you can change the list to install.

Use Set Collection .

A collection is a collection that cannot contain duplicate elements.

+2
source

equals() hashCode() LabelValue (hashCode ):

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

.

You must override the method equals()and hashCode()LabelValue.

And the method equals()should use the property nameas well as the method hashCode().

Then your code will work.

PS. I assume that your LabelValue objects can only be distinguished with the name property, which you seem to need anyway based on your question.

+1
source

Source: https://habr.com/ru/post/1535041/


All Articles