Collections: ArrayList, HashMap, TreeSet
Collections: ArrayList, HashMap, TreeSet and sorting with Arrays.sort.
Collections are Java's ready-made data structures. The three most useful:
• ArrayList — a variable-length list (the equivalent of C++'s vector);
• HashMap — a "key → value" dictionary for counting and grouping;
• TreeSet — a duplicate-free set that keeps its elements sorted.
Plus the static Arrays.sort method for sorting plain arrays.
Java
Sorting an array. Enter: 5, then 3 1 4 1 5
The loop for (int x : a) is the short "for each element" form.
Below, a HashMap counts how many times each number occurs: the getOrDefault method returns the accumulated value, or 0 when the key is not there yet.
Java
Counting occurrences. Enter: 6, then 1 2 2 3 3 3
Task: read n numbers and print how many distinct values there are (hint: put everything into a TreeSet and print its size()).
Mark the lesson as completed — the final lesson on fast input/output is ahead.