Count number of keys or values in hashmap

This example shows how to count the occurrences of key or value in a map. Creating sample map of data by initialize a map of months and then using java 8 and guava to count the number of times a key or value occurs. A comparable example demonstrates how to count keys or values in a groovy map.


Map<Integer, String> MONTHS = new HashMap<Integer, String>();

public void setUp() {

    MONTHS.put(new Integer(1), "January");
    MONTHS.put(new Integer(2), "February");
    MONTHS.put(new Integer(3), "March");
    MONTHS.put(new Integer(4), "April");
    MONTHS.put(new Integer(5), "May");
    MONTHS.put(new Integer(6), "June");
    MONTHS.put(new Integer(7), "July");
    MONTHS.put(new Integer(8), "August");
    MONTHS.put(new Integer(9), "September");
    MONTHS.put(new Integer(10), "October");
    MONTHS.put(new Integer(11), "November");
    MONTHS.put(new Integer(12), "December");

Java 8

public void count_value_in_map_using_java8() {

    Map<Integer, String> monthsStartWith_M = MONTHS.entrySet().stream()
            .filter(p -> p.getValue().startsWith("M"))
            .collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));

    assertEquals(2, monthsStartWith_M.size());

Google Guava

public void filter_map_by_value_entries_guava() {

    Predicate<Map.Entry<Integer, String>> monthLenthFour = new Predicate<Map.Entry<Integer, String>>() {
        public boolean apply(Entry<Integer, String> input) {
            return input.getValue().length() == 4;

    Map<Integer, String> monthsWithLengthFour = Maps.filterEntries(MONTHS,

    int count = monthsWithLengthFour.size();

    assertEquals(2, count);