簡體   English   中英

JAVA中的HashMap鍵比較和返回值

[英]HashMap Key Comparison and return values in JAVA

我想比較兩個不同的哈希圖的鍵說

Map<String, Float> map1 = new HashMap<>();
Map<String, Float> map2 = new HashMap<>();

MAP1:

<org.openjdk.jmh.samples.JMHSortBenchmark.collectionsSort,6691.679>
<org.openjdk.jmh.samples.JMHSortBenchmark.abcdSort,5151.45>
<org.openjdk.jmh.samples.JMHSortBenchmark.saasSort,5454.54>
<org.openjdk.jmh.samples.JMHSortBenchmark.xyzSort,888.22>

MAP2:

<org.openjdk.jmh.samples.JMHSortBenchmark.xyzSort,7448.362>
<org.openjdk.jmh.samples.JMHSortBenchmark.abcdSort,951.5>
<org.openjdk.jmh.samples.JMHSortBenchmark.lmnSort,4454.54>

並且如果它們匹配,例如“ org.openjdk.jmh.samples.JMHSortBenchmark.xyzSort”,那么我想返回map1和map2的<Key,Value>對,即,它必須返回

org.openjdk.jmh.samples.JMHSortBenchmark.xyzSort,888.22
org.openjdk.jmh.samples.JMHSortBenchmark.xyzSort,7448.362


org.openjdk.jmh.samples.JMHSortBenchmark.abcdSort,5151.45
org.openjdk.jmh.samples.JMHSortBenchmark.abcdSort,951.5

因為我想處理它們的值之間的差異並比較它們,即map1中的888.2和map2中的7448.362,從而將差異記錄到csv文件中。

我使用以下代碼:

for (Entry<String, Float> entry: map1.entrySet()) {
    if (map2.containsKey(entry.getKey())) {

        System.out.println("The matched value is" + entry.getValue() +"and Key is"+ entry.getKey());                            

    }
} 

但這可能僅返回map1的值,而不返回map2的值。

我會這樣做:

map1.keySet().retainAll(map2.keySet());

keySet()方法將為您提供地圖按鍵的設置視圖(!)。 keepAll()還將僅保留該集合中作為map2中的鍵的元素。 如果要保留map1的所有值,則可能需要先進行復制。

我為您提供了一個可行的解決方案。

static void test11()
{
    HashMap<String, Float> map1 = new HashMap<>();
    HashMap<String, Float> map2 = new HashMap<>();

    map1.put("org.openjdk.jmh.samples.JMHSortBenchmark.collectionsSort",(float) 6691.679);
    map1.put("org.openjdk.jmh.samples.JMHSortBenchmark.abcdSort1",(float) 5151.45);
    map1.put("org.openjdk.jmh.samples.JMHSortBenchmark.saasSort",(float) 5454.54);
    map1.put("org.openjdk.jmh.samples.JMHSortBenchmark.xyzSort",(float) 888.22);


    map2.put("org.openjdk.jmh.samples.JMHSortBenchmark.xyzSort", (float) 7448.362);
    map2.put("org.openjdk.jmh.samples.JMHSortBenchmark.abcdSort", (float) 951.5);
    map2.put("org.openjdk.jmh.samples.JMHSortBenchmark.lmnSort", (float) 4454.54);

    for(String key: map1.keySet())
    {
        // use key to search 2nd list, will be null if no matching key found
        Float map2data = map2.get(key);

        if (null == map2data)
        {
            // Current key not found
        }
        else
        {
            Float map1data = map1.get(key);

            // You can do you operations here with matching keys data here
        }
    }
}

希望這會有所幫助。 :-)

暫無
暫無

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

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