简体   繁体   中英

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

I need to know how many hashmaps have the specific key in an array of hashmaps.

How can I get that number without going through the whole array in a loop? something like

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

From a performance standpoint, there's no way of achieving this without going through all the maps, with O(n) complexity (note that containsKey has a O(1) complexity in a HashMap ).

If the issue is just avoiding the clunky syntax of writing a loop, Java 8 offers a neat way of doing this with streaming APIs:

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

EDIT:
According to the comment bellow, it's not an array, but an ArrayList . The same principal still holds, but since you have an actual Collection , you could just call .stream :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM