【问题标题】:Filter unique objects from an ArrayList based on property value of the contained object根据包含对象的属性值从 ArrayList 中过滤唯一对象
【发布时间】:2013-03-08 06:12:16
【问题描述】:

如何从数组列表中过滤唯一对象。

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

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

那是city.getName()

【问题讨论】:

  • 如果可能,考虑使用 HashMap。
  • 这里的问题不是数据结构,imo

标签: java arraylist


【解决方案1】:
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);

        }

【讨论】:

    【解决方案2】:

    假设您可以更改要设置的列表。

    请改用Set Collection

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

    【讨论】:

      【解决方案3】:

      覆盖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;
      }
      

      【讨论】:

        【解决方案4】:

        这是解决它的一种方法。

        你应该重写LabelValue的equals()方法和hashCode()

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

        那么你的代码就可以工作了。

        PS。我假设您的 LabelValue 对象可以仅通过 name 属性来区分,根据您的问题,这似乎是您无论如何都需要的。

        【讨论】:

          猜你喜欢
          • 2018-04-07
          • 2018-09-08
          • 2015-05-30
          • 2023-03-12
          • 2018-12-25
          • 1970-01-01
          • 2018-05-25
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多