020-004-001
Advanced Map: Word Frequency Counter
Hard
Problem Description
In this problem, you will create a program that receives a list of words as input, counts the frequency of each word using HashMap.merge(), sorts the results in descending order by frequency (alphabetical order for ties), and displays the result to standard output.
Frequency Counting Pattern
Learn efficient counting using HashMap.getOrDefault() and merge().
Counting method
Map<String, Integer> freq = new HashMap<>();
For (String word : words) {
Freq.merge(word, 1, Integer::sum);
}Sorting Method
List<Map.Entry<String, Integer>> entries = new ArrayList<>(freq.entrySet());
Entries.sort((a, b) -> {
Int cmp = b.getValue().compareTo(a.getValue()); // descending
Return cmp != 0 ? Cmp : a.getKey().compareTo(b.getKey()); // alphabetical if same
});Learning Points
- merge() uses initial value if key missing, applies function if exists
- Comparator chaining achieves compound sort conditions
- entrySet() retrieves key-value pairs together
Test Cases
※ Output examples follow programming industry standards
Normal case
Input:
7 apple banana apple orange banana apple grape
Expected Output:
apple: 3 banana: 2 grape: 1 orange: 1
Boundary case
Input:
5 cat cat cat cat cat
Expected Output:
cat: 5
Your Solution
Current Mode:● My Code
99
1
2
3
4
5
6
7
8
9
10
›
⌄
⌄
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Write your code here
sc.close();
}
}
0 B / 5 MB
You have 10 free executions remaining
