java - 如何计算Hashmap数组中特定键的Hashmap出现次数?

标签 java android arrays hashmap

我需要知道在 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/

相关文章:

安卓jar目录

android - 如何使用 Intent 从第三个 Activity 返回到第二个 Activity

Android Studio For 循环开启

arrays - VBA Excel 2010 : convert string array into int array

android - EditText onLongClick();隐藏剪切/复制/全选栏

c++ - 如何*正确*地将 std::string 转换为无符号 char[] 数组。我想我做错了,有人指出我正确的方向吗?

java - 如果编译器可以内联日志调用,为什么还要在日志 API 中使用 lambda 表达式

java - 如何访问Camel errorHandler中的异常?

java - 为什么struts2 html table会多生成一个<tr></tr>

java - 使用多个 AnntationProcessor 找不到 FluentFuture 类