簡體   English   中英

如何比較 Java 中的 hashmap?

[英]how to compare hashmap in Java?

我有兩個HashMaps ,我想比較值的鍵,如果它們不同,則返回兩個鍵之間的差異

public class AsciiCount {
    public static void main(String args[]) {
        String input = "Hello";
        String input1 = "eHllo";
        
        Store obj1= new Store();
        
        String orderOfString = obj1.CheckOrder(input);
        System.out.println(orderOfString);
        
        HashMap inputLocation = obj1.getCharacterLocation(input);
        HashMap input1Location = obj1.getCharacterLocation(input1);
        System.out.println(inputLocation);
        System.out.println(input1Location);
    }
}
// OUTPUT of print
// inputLocation = {0=72, 1=101, 2=108, 3=108, 4=111}
// input1Location = {0=101, 1=72, 2=108, 3=108, 4=111}

例子

這里

72 的鍵在inputLocation中為 0,但 72 的鍵在input1Location中為 1

101 的鍵在inputLocation中為 1,但 101 的鍵在input1Location中為 0

所以 output 應該是2 (即更改次數)

如果需要的是已更改的值的計數,則此代碼應該可以工作。

HashMap inputLocation = obj1.getCharacterLocation(input);
HashMap input1Location = obj1.getCharacterLocation(input1);
int diffCount = 0;
for (Object key : inputLocation.keySet()) {
     if ( !inputLocation.get(key).equals(input1Location.get(key))){
         diffCount++;           
     }
}

diffCount 將為您提供更改值的計數。

這只是一些粗略的代碼,請隨時更新。 我建議您使用HashMap<Integer, Integer>而不是普通的HashMap ,因為這樣可以保證類型安全。

您必須在兩個對象 HashMaps 的 keySet() 上使用 equals 來比較單個值。 有了這個,您可以比較/獲取 Hash 的關鍵參數。 在此之后,您必須獲取 HashMap 的值來比較該值。 但如果您需要比較整個 hash 只需使用等號即可。

您的代碼將如下所示:

public class AsciiCount {
public static void main(String args[]) {
    String input = "Hello";
    String input1 = "eHllo";
    
    Store obj1= new Store();
    
    String orderOfString = obj1.CheckOrder(input);
    System.out.println(orderOfString);
    HashMap inputLocation = obj1.getCharacterLocation(input);
    HashMap input1Location = obj1.getCharacterLocation(input1);
    System.out.println(inputLocation);
    System.out.println(input1Location);
    HashMap input1Location = obj1.getCharacterLocation(input1);

    // This is the comparison of the value from the key
    inputLocation.get(inputLocation.keySet()[2]).equals(input1Location.get(input1Location.keySet()[2]);
    // 2 is the second argument of the key value in the HashMap

    // This is the comparison of the two hashes
    inputLocation.equals(input1Location);

    // OUTPUT of print
    // inputLocation = {0=72, 1=101, 2=108, 3=108, 4=111}
    // input1Location = {0=101, 1=72, 2=108, 3=108, 4=111}
    // true
    // false


}}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM