AlgoViz

Java Collections

Easy

Java's equivalent toolbox

Problem

Java's Collections Framework is the equivalent toolbox: ArrayList, HashMap, HashSet, Stack, ArrayDeque, PriorityQueue, plus Collections.sort. Reach for these instead of raw arrays for dynamic data.

In simple words

Java's ready-made toolboxes: lists, maps, sets, and sorting.

The idea

The Collections Framework mirrors the STL: ArrayList for dynamic arrays, HashMap and HashSet for O(1) lookup, TreeMap for sorted keys, ArrayDeque for stacks and queues, PriorityQueue for heaps. The interfaces matter more than the classes — code against List and Map, not ArrayList and HashMap.

The trick

  • `ArrayDeque` beats `Stack` and `LinkedList` for both stack and queue use.
  • `PriorityQueue` is a min-heap by default — the opposite of C++.
  • `HashMap.getOrDefault(k, 0)` and `merge` make frequency counting a one-liner.
3
1
2
1
0
1
2
3
size4

Step 1 of 4. A list keeps what you put in it, in the order you put it in. Values: 3, 1, 2, 1. size 4.

1/4
Optimal
timespace
1List<Integer> list = new ArrayList<>();2Map<String,Integer> freq = new HashMap<>();3Collections.sort(list);

Input

array
[3, 1, 2, 1]

Memory

size
4
keys
put in
kept

Check yourself

1 quick question about this walkthrough. A wrong answer costs nothing.

Examples

Example 1

Input:
List<Integer> v = List.of(3,1,2); Collections.sort(new ArrayList<>(v))
Output:
[1, 2, 3]
Explanation:
ArrayList, HashMap, HashSet and Collections.sort are Java's equivalents of the C++ toolbox on the previous page.

Example 2

Input:
map.merge("a", 1, Integer::sum) on an empty HashMap
Output:
{a=1}
Explanation:
merge covers the 'first time I have seen this key' case, the way operator[] does in C++.

Finished the walkthrough? Add it to your streak.