Use ArrayList and HashMap in practice
Store variable-size data and aggregate values by key.
- Use Java collections to compute grouped totals.
ArrayList stores a growable ordered list, and HashMap stores key-value pairs for fast lookup and aggregation. Collections are core tools in real Java services and data processing code.
1import java.util.ArrayList;
2import java.util.HashMap;
3
4ArrayList<String> regions = new ArrayList<>();
5regions.add("north");
6regions.add("south");
7regions.add("north");
8
9HashMap<String, Integer> counts = new HashMap<>();
10for (String region : regions) {
11 counts.put(region, counts.getOrDefault(region, 0) + 1);
12}
13
14System.out.println(counts.get("north"));2
Use getOrDefault(key, fallback) when the key may be missing. This pattern is common in analytics and operational scripts where you count or sum values by category.
Key takeaways
Use Java collections to compute grouped totals.
Java checks types as it compiles your source.
Use compiler messages as clues about what needs fixing.
Lesson quiz
4 questions · pass with 3 correct · up to 50 XP
Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.
Practice: write Java
Write Java in the editor and run it against sample input with a remote compiler. Your code is sent to Compiler Explorer to compile and run.
Count tag frequencies
Read an integer n, then n tag names (strings). Print the count of java tags.
- Two java tags
- No java tags
Java is compiled and run by Compiler Explorer (godbolt.org), a free public service. Your source code and test input are sent to that service.
Questions about this lesson
Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.
Loading posts…