[英]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.