[英]Filter unique objects from an ArrayList based on property value of the contained object
我将如何从arraylist过滤唯一对象。
List<LabelValue> uniqueCityListBasedState = new ArrayList<LabelValue>();
for (LabelValue city : cityListBasedState) {
if (!uniqueCityListBasedState.contains(city)) {
uniqueCityListBasedState.add(city);
}
}
这是我的代码。 但是问题是我需要过滤的对象不是该对象,而是该对象内部属性的值。 在这种情况下,我需要排除具有名称的对象。
那是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);
}
覆盖LabelValue
的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;
}
这是解决它的一种方法。
您应该重写LabelValue的equals()
方法和hashCode()
。
equals()
方法应使用name
属性, hashCode()
方法也应使用。
然后您的代码将起作用。
PS。 我假设您的LabelValue对象可以仅通过name属性来区分,这似乎仍然是基于您的问题而需要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.