Notes
The idea
Pick the collection by the question you need to answer. A List keeps order and allows repeats: search results, table rows, steps. A Set keeps unique values and answers is it there quickly: emails, skus, ids. A Map stores key and value pairs and answers what is the value for this key: the price for a sku, the count for a word. Choosing right makes the test shorter and the intent obvious.
- List "in what order?" "how many, with repeats?" search results, rows
- Set "is it there?" "are they all unique?" emails, SKUs
- Map "what is the value for this key?" sku → price, word → count
List
A list keeps items in order, by index from zero, and allows duplicates. Here four skus, with BK one oh one twice: the size is four, item zero is BK one oh one, and contains finds the mug. Notice the pattern: the variable's type is the List interface, and ArrayList is the implementation. That is polymorphism from the last episode, and it lets you swap the implementation later without changing the rest of the code.
List<String> skus = new ArrayList<>(
List.of("BK-101", "MG-201",
"BK-101", "ST-501"));
skus.size() // 4
skus.get(0) // "BK-101"
skus.contains("MG-201") // true
skus.add("TS-301");
for (String s : skus) { ... }
List<String>: interface type
ArrayList: the implementation Immutable lists
List of creates an immutable list: try to add to it and Java throws an unsupported operation exception. That is perfect for expected values in a test, because nothing can change them by accident. To make a changeable list from one, wrap it in new ArrayList, as in the last beat. Two lists are equal when they hold the same items in the same order, whatever their implementation, which is exactly what an assertion needs.
var expected = List.of(
"Green Build Mug",
"Red Build Mug");
expected.add("x");
// UnsupportedOperationException
List.of(1, 2).equals(
Arrays.asList(1, 2)) // true
// lists equal = same items,
// same order Set
A set keeps only unique values. Put the four skus into a hash set and the size is three, because the duplicate is dropped. Choose the implementation by order. A hash set is fastest but has no predictable order. A linked hash set keeps the order items were added. A tree set keeps them sorted. A classic quick check: if a list's size differs from the size of a set made from it, the list has duplicates.
// from BK-101, MG-201, BK-101, // ST-501 new HashSet<>(skus).size() // 3 // fast, NO predictable order new LinkedHashSet<>(skus) // [BK-101, MG-201, ST-501] // keeps insertion order new TreeSet<>(skus) // sorted order dupes: list.size() != set.size()
Map
A map stores key and value pairs. Put the price of each sku, then get the mug's price by its key: fifteen hundred cents. Get or default returns a fallback, here zero, when the key is missing, instead of null. Contains key checks for a key. To walk through a map, loop over its entry set, which gives each key and value. Keys are unique: putting the same key again replaces its value.
Map<String, Long> price =
new HashMap<>();
price.put("MG-201", 1500L);
price.put("BK-101", 1250L);
price.get("MG-201") // 1500
price.getOrDefault("XX", 0L)
// 0
price.containsKey("BK-101")
for (var e : price.entrySet())
e.getKey() + "=" + e.getValue() Counting
Counting is a pattern you will use constantly, and it is behind many interview questions. For each item, merge puts one if the key is new, or adds one to the existing count. Counting the skus gives BK one oh one twice, and the others once. A tree map prints keys sorted. Count the characters in the word testing with a linked hash map, and you get t twice and every other letter once, in the order they first appear.
Map<String, Integer> counts =
new TreeMap<>();
for (String s : skus)
counts.merge(s, 1, Integer::sum);
// {BK-101=2, MG-201=1, ST-501=1}
// characters in "testing":
// LinkedHashMap → {t=2, e=1,
// s=1, i=1, n=1, g=1} Sorting
To sort a list, use collections dot sort, or the list's own sort method with a comparator. Sorting four ShopRung prices gives four ninety nine first and the headphones last. Reverse order flips it. For objects, comparator dot comparing with a method reference sorts by any field, like price. A common test: sort the prices you got from the API yourself, and assert the page showed them in the same order when the user chose price, low to high.
var prices = new ArrayList<>(
List.of(1500L, 499L, 12999L,
2550L));
Collections.sort(prices);
// [499, 1500, 2550, 12999]
prices.sort(
Comparator.reverseOrder());
// [12999, 2550, 1500, 499]
products.sort(Comparator
.comparing(Product::priceCents)); In a test
Here is how this looks in a real test. Search ShopRung for MUG in capitals. Turn the items into a list of names, and assert it equals a list of the two mug names, which checks both the content and the order. If order does not matter, compare sets instead. And to check that every sku in the response is unique, put them in a set and compare its size with the number of items. You will use streams like this in the next episode.
// GET /api/products?q=MUG List<String> names = items .stream().map(Item::name) .toList(); assertEquals(List.of( "Green Build Mug", "Red Build Mug"), names); Set<String> skus = ...; assertEquals(skus.size(), n);
Trap 1
Trap one. Remove an item from a list while a for each loop is walking it, and Java throws a concurrent modification exception, because the loop's view of the list is now out of date. Use remove if with a condition instead, which does the loop and the removal safely, or an iterator with its own remove method. This error confuses many beginners, because the name suggests threads, but here there is only one.
for (String s : list)
if (s.equals("a"))
list.remove(s); // throws
// do this instead:
list.removeIf(
s -> s.equals("a"));
// or use an Iterator and
// iterator.remove() Trap 2
Trap two. A hash set or hash map has no promised order. It may print in one order today and a different one with more data or a different Java version. A test that compares a hash set's to string with a fixed text will pass for months and then fail for no visible reason, which is a classic flaky test. Compare sets with sets, maps with maps, or use the linked or tree versions when order matters.
- a HashMap may print in one order today and another after a Java update or more data
- flaky test: assertEquals("[a, b]", hashSet.toString())
- fix: compare sets with sets, or use LinkedHash / Tree
Common mistakes
Collection mistakes in test code. Using a list when you need a set, which makes contains slow and lets duplicates through. Asserting the order of a hash set or map. Removing inside a for each loop. Calling get on a missing key, getting null, and crashing later. Trying to change a list made with list of. And comparing two Integer objects with double equals, which works for small numbers and fails above one hundred and twenty seven. Use equals.
- list when you need a set (slow contains, duplicates)
- asserting hash order
- removing inside for-each
- get() on a missing key → null → NullPointerException
- modifying List.of values
- == on Integer > 127 (use equals)
Say it like this
In the interview, say: a list is ordered and allows duplicates, a set holds unique values, and a map maps keys to values. Hash map is fastest with no order, linked hash map keeps insertion order, and tree map sorts by key. Then connect it to testing: I use sets for uniqueness checks, maps for lookups and counts, and immutable lists for expected values. Expect a follow up coding question, like counting characters with a map.
- "A List is ordered and allows
- duplicates; a Set holds unique
- values; a Map maps keys to values. HashMap is fastest
- with no order, LinkedHashMap
- keeps insertion order, TreeMap
- sorts by key. In tests I use
- Sets for uniqueness checks
- and Maps for counts."