簡體   English   中英

考慮到 Hashmap,我如何在 for 循環中使用額外的檢查?

[英]How can I use additional checks in the for loop considering Hashmap?

我創建了兩個哈希圖,我想在同一個 for 循環中迭代它們。

HashMap<String,Double> hashmapA = new HashMap<>();
HashMap<String,Double> hashmapB = new HashMap<>();

因此,如果我按如下方式迭代hashmapA的元素:

for(String map1:hashmapA.keyset()){
...
}

如何在同一個循環中迭代hashmapB的值? 實際上,我不想使用內循環。

迭代器是使用keysetentrySet的最佳選擇之一

Iterator hmIterator1 = hashmapA.entrySet().iterator(); 
Iterator hmIterator2 = hashmapB.entrySet().iterator(); 

 while (hmIterator1.hasNext() && hmIterator2.hasNext()) { 

       hmIterator1.next();
       hmIterator2.next();

    } 

如果您只想遍歷所有鍵:

只需從第一個Map的鍵中創建一個新的HashSet並添加第二個Map的鍵:

Collection<Map.Entry<String,Double>> entries=new HashSet<>(hashmapA.entrySet());
keys.addAll(hashmapB.entrySet());
for(Map.Entry<String,Double> entry:entries){
    String key=entry.getKey();
    Double value=entry.getValue();
    ...
}

這也可以使用 Java 8 Streams 來完成:

for(Map.Entry<String,Double> entry: Stream.concat(hashmapA.entrySet().stream(),hashmapB.entrySet().stream()){
     String key=entry.getKey();
    Double value=entry.getValue();
    ...
}

如果你只想要地圖的交集,你可以使用:

Collection<String> keys=new HashSet<>(hashmapA.keySet());
keys.retainAll(hashmapB.keySet());
for(String key:keys){
    Double aValue=hashmapA.get(key);
    Double bValue=hashmapB.get(key);
    ...
}

或者(使用流):

for(String key: hashmapA.entrySet().stream().filter(k->hashmapB.containsKey(k))){
    Double aValue=hashmapA.get(key);
    Double bValue=hashmapB.get(key);
    ...
}

正如@bsaverino在評論中所說:

關於你提到的最新言論@Hami然后就遍歷的鍵hashmapA和使用hashmapB.containsKey(...)可能已經足夠了。

以下內容也適用於您的情況:

for(String key:hashmapA.keySet()){
    if(hashmapB.containsKey(key){
        Double aVal=hashmapA.get(key);
        Double bVal=hashmapB.get(key);
    }
}

暫無
暫無

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

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