【问题标题】:How to merge to HashSets with partially equal Objects?如何合并两个具有部分相等对象的哈希集?
【发布时间】:2023-04-01 14:42:01
【问题描述】:

我有一个 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 循环(执行耗时)并覆盖哈希集,但我不确定这种方法。

【问题讨论】:

  • 使用可以使用名称作为哈希图中的键,并且每次键已经存在时调用该对象的更新方法

标签: java hashset


【解决方案1】:

使用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

【讨论】:

    【解决方案2】:

    没有部分相等的东西。您的方法equals() 返回truefalse。在您的情况下,您所说的平等仅由个人身份决定。 IE。如果您添加一个具有相同 id 的人,则其他任何事情都无关紧要,即使 visits 值不同,两个 Person 实例也将被判断为相等。因此,如果您将 Person 实例存储在集合中并添加一个 id 为 1 的 Person - 如果该集合已经包含一个 id 为 1 的 Person ,则旧的将被新的替换。还要记住Set 没有订单。如果您想保留订单,请使用SortedSetList。但是如果你使用List,你将不得不编写代码来确保你自己不允许重复

    【讨论】:

      猜你喜欢
      • 2013-04-30
      • 2011-07-23
      • 2011-10-21
      • 2021-03-25
      • 1970-01-01
      • 2019-05-03
      • 1970-01-01
      • 1970-01-01
      • 2012-09-24
      相关资源
      最近更新 更多