[英]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)復雜度(請注意, containsKey
在HashMap
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.