Skip to content
CodeKruPro

Counting words with merge and getOrDefault

Predict the outputMediumJava onlyAsked in: Capgemini, ISS STOXX
Main.java
import java.util.*;

public class Main {
    public static void main(String[] args) {
        String[] words = {"b", "a", "b", "c", "b", "a"};
        Map<String, Integer> counts = new TreeMap<>();
        for (String w : words) {
            counts.merge(w, 1, Integer::sum);
        }
        System.out.println(counts);
        System.out.println(counts.getOrDefault("z", 0));
        System.out.println(counts.get("z"));
    }
}

This question is part of Pro+

Pro+ opens every question in Interview Prep and the mock interview. Every article and the first 2 questions of each topic stay free. Hands-on Selenium and API tasks follow their course lesson's own lock.

See Pro+

Already have Pro+? Sign in