如何合并到具有部分相等对象的HashSet?

时间:2019-08-14 10:24:31

标签: java hashset

我有一个ArrayList data,其中包含类型为Person的对象,该对象每n秒更新一次,并具有现有数据的总量。 为了在表中显示此数据,我曾经clear()观察了一个ObservableList,并使用addAll(data)避免了GUI异常。

我想使用HashSet作为Observable集合,我想知道是否存在一种有效的方法来从HashSet中更新对象(如果它只是部分相等的话)。

代码:

class Person {
   int id;
   String name;
   int visits;  //this value can be different

   @Override
   int hashCode() {
   //...
   }

   @Override
   boolean equals() {
   //...
   }

}


class Main {
   static void main(String[] args) {
      List<Person> data = new ArrayList<>();
      data.add(new Person(1, Max, 4);
      data.add(new Person(2, Richard, 7); 
      data.add(new Person(3, Tom, 4); 

      Set<Person> set = new HashSet<>();
      set.addAll(data);

      // new Data incoming
      // could be the same Person (all 3 variables same)
      // could be existing Person but with changed variables (id stays the same)
      // could be completely new Person (new id)


   }
}

所需的输出:

如果新数据与现有的Person添加在一起但变量不同 new Person(1, Max, 50); 该位置的索引应删除Max并添加50次访问的新Max(可能在同一位置) 或者最好将可变访问次数更改为50。

如果所有数据都相同(用equals()和hashCode()检查):则不应添加或删除任何内容

如果HashSet中没有新人(具有新ID),则应添加

如何实现? 我尝试使用2 for循环(这会耗费执行时间)并覆盖哈希集,但我不确定这种方法。

2 个答案:

答案 0 :(得分:2)

使用Map,而不是Set

  List<Person> data = new ArrayList<>();
  data.add(new Person(1, Max, 4);
  data.add(new Person(2, Richard, 7); 
  data.add(new Person(3, Tom, 4); 

  Map<Integer, Person> map = new HashMap<>();
  data.forEach(person -> map.put(person.getId(), person));

  // new Data incoming
  // could be the same Person (all 3 variables same)
  // could be existing Person but with changed variables (id stays the same)
  // could be completely new Person (new id)
  Person newPerson = ...;
  map.put(newPerson.getId(), newPerson);

如果要按ID排序,可以使用TreeMap,如果要按输入顺序排序,可以使用LinkedHashMap

答案 1 :(得分:1)

没有部分相等的东西。您的方法equals()返回truefalse。在您的情况下,您所说的平等仅由个人ID决定。即如果您添加一个具有相同ID的人员,那么其他任何事情都没有关系,即使visits的值不同,两个Person实例也将被视为相等。因此,如果将Person实例存储在集合中并添加ID为1的Person-如果集合已经包含ID为1的Person,则旧的将被新的替换。另外请记住,Set没有顺序。如果要保留订单,请使用SortedSetList。但是,如果您使用List,则必须编写代码,以确保自己不允许重复

相关问题