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

arraylistjava

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

Best Answer

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

        }