我需要知道在 HashMap 数组中有多少 HashMap 具有特定键。
如何在不循环遍历整个数组的情况下获得该数字?像
int occurrences = Collections.frequency(TheHashmapArray, ["specificKey",*]);
最佳答案
从性能的角度来看,如果不遍历所有映射就无法实现这一点,复杂度为 O(n)(请注意 containsKey
在 中的复杂度为 O(1) HashMap
).
如果问题只是避免编写循环的笨拙语法,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();
关于java - 如何计算Hashmap数组中特定键的Hashmap出现次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31726439/