2013-03-08 74 views
0

如何过滤来自数组列表的唯一对象。根据包含对象的属性值从ArrayList过滤唯一对象

List<LabelValue> uniqueCityListBasedState = new ArrayList<LabelValue>(); 
for (LabelValue city : cityListBasedState) { 
    if (!uniqueCityListBasedState.contains(city)) { 
     uniqueCityListBasedState.add(city); 
    } 
} 

这是我的代码。但问题是我需要过滤的不是对象,而是过滤该对象内的属性的值。在这种情况下,我需要排除具有名称的对象。

也就是说city.getName()

+1

考虑如果可能的话使用HashMap中。 – 2013-03-08 06:17:16

+1

它不是这里问题的数据结构。,imo – smk 2013-03-08 06:18:00

回答

1

这是解决这个问题的方法之一。

您应该覆盖LabelValue的equals()方法和hashCode()

equals()方法应该使用name属性,所以应该使用hashCode()方法。

然后你的代码将工作。

PS。我假设你的LabelValue对象可以用name属性来区分,这就是你根据你的问题似乎需要的东西。

2

假设您可以更改要设置的列表。使用Set Collection代替。

Set是一个集合,它不能包含重复的元素。

2

覆盖的LabelValueequals()hashCode()方法(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; 
} 
6
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); 

     } 
相关问题