散列表键值对比较以查找唯一对。

huangapple 未分类评论45阅读模式
英文:

hashtable key-value pair comparison to find out unique pair

问题

public static void main(String[] args) {
    Hashtable<String, String> ht1 = new Hashtable<>();
    ht1.put("10", "ghu");
    ht1.put("20", "lo");

    Hashtable<String, String> ht2 = new Hashtable<>();
    ht2.put("10", "ko");
    ht2.put("20", "lo");

    // Compare and find unique entries
    for (String key : ht1.keySet()) {
        String value1 = ht1.get(key);
        String value2 = ht2.get(key);
        
        if (!value1.equals(value2)) {
            System.out.println("(" + key + ", " + value1 + "); this is from first hashtable");
            System.out.println("(" + key + ", " + value2 + "); this is from second hashtable");
        }
    }
}
英文:
public static void main(String[] args) {
Hashtable&lt;String, String&gt; ht1= new Hashtable&lt;&gt;();
ht1.put(&quot;10&quot;, ghu&quot;);
ht1.put(&quot;20&quot;, &quot;lo&quot;);


Hashtable&lt;String, String&gt; ht2= new Hashtable&lt;&gt;();
ht2.put(&quot;10&quot;, &quot;ko&quot;);
ht2.put(&quot;20&quot;, &quot;lo&quot;);

how can i compare both hash table by using key-value pair to each other find unique entry of key-value pair from both hash table..

expected output...
("10", "ghu"); this is from first hashtable
("10", "ko"); this is from second hashtable

答案1

得分: 0

HashTable保存一个Entry,可以通过使用getEntrySet()方法来提取。因此,您应该编写类似下面的伪代码。您可能需要对下面的代码片段进行一些更改,以使其能够编译。

Set<Entry> entrySet = ht1.getEntrySet(); // 获取所有值
// 遍历这些值
for (Entry entry : entrySet) {
    String htVal = ht2.get(entry.getKey());
    if (htVal != null && htVal.equals(entry.getValue())) {
        // 非唯一 - 忽略
    } else {
        // 存储ht1和ht2中唯一的条目
    }
}
英文:

HashTable keeps an Entry which can get extracted by using getEntrySet() method.
Thus you should something like pseudoCode below. You might need to make some change to below snippet to make it compilable.

Set&lt;Entry&gt; entrySet= ht1.getEntrySet();//get all values
      //iterate over those
      for(Entry entry :entrySet ){
            String htVal = ht2.get(entry.getKey());
             if (htval!=null &amp;&amp; htVal.equals(entry.getValue())){
                //non unique -ignore
                   }else{
                //store ht1 and ht2 unique entries
                  }
              }

huangapple
  • 本文由 发表于 2020年4月4日 21:48:19
  • 转载请务必保留本文链接:https://java.coder-hub.com/61029075.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定