簡體   English   中英

如何使用Hashmaps數組中的特定鍵計算Hashmaps的出現次數?

[英]How to count the number of occurrences of Hashmaps with an specific key in a array of Hashmaps?

我需要知道有多少個hashmaps在一個hashmaps數組中有特定的鍵。

如何在不循環遍歷整個數組的情況下獲取該數字? 就像是

int occurrences = Collections.frequency(TheHashmapArray, ["specificKey",*]);

從性能的角度來看,沒有經過所有映射就無法實現這一點,具有O(n)復雜度(請注意, containsKeyHashMap containsKey具有O(1)復雜度)。

如果問題只是避免編寫循環的笨拙語法,Java 8提供了一種使用流API的簡潔方法:

Map<String, String>[] mapsArray = // get the value
long numMaps =
    Arrays.stream(mapsArray).filter(p -> p.containsKey("some_key")).count();

編輯:
根據下面的評論,它不是一個數組,而是一個ArrayList 同樣的原則仍然存在,但由於你有一個實際的Collection ,你可以只調用.stream

ArrayList<HashMap<String, String>> mapsArray =  // get the value
long numMaps = mapsArray.stream().filter(p -> p.containsKey("some_key")).count();

暫無
暫無

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

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