QA AND TEST AUTOMATION · PART 2 · PROGRAMMING FOR TESTERS · JAVA · 23 OF 112

Java Collections for Testers: List, Set, Map

The three collections test code uses all day: List for ordered results, Set for uniqueness, Map for lookups and counts, with the right implementation of each (ArrayList, HashSet, LinkedHashSet, HashMap, TreeMap), sorting with Comparator, immutable List.of, and the traps: ConcurrentModificationException and order you should not rely on. All checked on ShopRung data.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
  49. 49
  50. 50
  51. 51
  52. 52
  53. 53
  54. 54
  55. 55
  56. 56
  57. 57
  58. 58
  59. 59
  60. 60
  61. 61
  62. 67
  63. 68
  64. 69
  65. 70
  66. 71
  67. 72
  68. 73
  69. 74
  70. 75
  71. 76
  72. 77
  73. 78
  74. 79
  75. 80
  76. 81
  77. 82
  78. 83
  79. 84
  80. 85
  81. 86
  82. 87
  83. 88
  84. 89
  85. 90
  86. 91
  87. 92
  88. 93
  89. 94
  90. 95
  91. 96
  92. 97
  93. 98
  94. 99
  95. 100
  96. 101
  97. 102
  98. 103
  99. 104
  100. 105
  101. 106
  102. 107
  103. 108
  104. 109
  105. 110
  106. 111
  107. 112
1 / 14

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • List for order
  • Set for uniqueness
  • Map for lookups and counts
  • sort with Comparator
  • avoid hash-order and removal traps

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.

Which one?
  • 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 basics
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.

List.of is immutable
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.

Set implementations
// 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 basics
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.

Count with merge
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.

Sorting
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.

Search returns both mugs
// 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.

ConcurrentModificationException
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.

Do not rely on hash order
  • 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.

Avoid these
  • 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.

In the interview
  • "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."

Interview questions

Q1What is the difference between List, Set and Map?

A List is an ordered collection that allows duplicates; a Set holds unique elements; a Map stores key-value pairs with unique keys.

Q2What is the difference between HashMap, LinkedHashMap and TreeMap?

HashMap gives fast access with no guaranteed order; LinkedHashMap keeps insertion order; TreeMap keeps keys sorted.

Q3How do you find duplicates in a list?

Add items to a Set and check whether add() returns false, or compare list.size() with new HashSet<>(list).size(); to count, use a Map with merge.

Q4What is the difference between ArrayList and LinkedList?

ArrayList is backed by an array: fast index access, slower inserts in the middle. LinkedList is a doubly linked list: fast inserts and removals at the ends, slow index access. ArrayList is the usual default.

Q5Why do you get ConcurrentModificationException?

Because the collection was modified (for example remove()) while being iterated with a for-each loop. Use removeIf or an Iterator's remove().

Q6What does List.of return?

An immutable list; add or remove throws UnsupportedOperationException, and null elements are not allowed.

Q7How do you count character occurrences in a string?

Loop over the characters and use map.merge(c, 1, Integer::sum) on a LinkedHashMap (keeps first-seen order) or a TreeMap (sorted).

Q8Why might a test that prints a HashSet be flaky?

HashSet has no guaranteed iteration order, so the printed order can change; compare collections by content or use an ordered implementation.