Command Palette

Search for a command to run...

Back to the lesson: Topic 9.1 — The Collections Map
Core Java · Example 3 of 3

The Collections helper class

The Collections Framework is a family of interfaces (List, Set, Queue, Deque, Map) and the classes that implement them (ArrayList, HashSet, HashMap, ArrayDeque and more). You choose an interface for the behaviour you need and an implementation for the performance you need.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Given the words {"red", "blue", "red", "green", "blue", "red"}, print the distinct words in first-seen order and the count of each word in sorted order.

02

Write static <T> List<T> lastN(List<T> list, int n) that returns a new list with the last n elements (or all of them if there are fewer). Print lastN(List.of(1, 2, 3, 4, 5), 2) and lastN(List.of(1), 3).

03

Using only Collections helpers, print the largest and smallest of List.of("kiwi", "apple", "mango") and the list sorted in reverse alphabetical order.

Explain it without notes

01

Draw the main interfaces of the Collections Framework and say where Map fits.

02

What is the difference between Collection and Collections?

03

Why should you declare variables as List<String> rather than ArrayList<String>?

04

Why can't collections hold primitives, and what does that cost?

The Collections helper class
Sign in to run this example in your browser.

Expected output

max: 91, min: 55
how many 91s: 2
sorted: [55, 68, 72, 91, 91]
index of 72: 2
reversed: [91, 91, 72, 68, 55]
swapped ends: [55, 91, 72, 68, 91]
nCopies: [-, -, -]
read-only view refused add