Java 根据包含对象的属性值从ArrayList中筛选唯一对象
如何从arraylist中筛选唯一对象Java 根据包含对象的属性值从ArrayList中筛选唯一对象,java,arraylist,Java,Arraylist,如何从arraylist中筛选唯一对象 List<LabelValue> uniqueCityListBasedState = new ArrayList<LabelValue>(); for (LabelValue city : cityListBasedState) { if (!uniqueCityListBasedState.contains(city)) { uniqueCityListBasedState.add(city);
List<LabelValue> uniqueCityListBasedState = new ArrayList<LabelValue>();
for (LabelValue city : cityListBasedState) {
if (!uniqueCityListBasedState.contains(city)) {
uniqueCityListBasedState.add(city);
}
}
这是我的密码。但问题是,我需要过滤的不是对象,而是对象内部属性的值。在这种情况下,我需要排除具有名称的对象
这就是城市。getName这里有一种解决方法 您应该重写LabelValue的equals方法和hashCode equals方法应该使用name属性,hashCode方法也应该使用 那么你的代码就可以工作了
另外,我假设您的LabelValue对象可以仅通过name属性进行区分,而这正是基于您的问题您似乎需要的。假设您可以将列表更改为set 改用新的 集合是不能包含重复元素的集合 在这种情况下,不必覆盖LabelValue hashCode的equals和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;
}
如果可能的话,考虑使用HASMAP。这不是数据结构,这是问题所在。
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);
}