So far you’ve worked with plain arrays. Real Java code uses the Collections framework: List, Set and Map. Interviewers love collection questions because the code is short, so the whole conversation is about choice:
| You want | Use | Order | Duplicates |
|---|---|---|---|
| a resizable array | ArrayList |
insertion order | allowed |
| unique values, fastest | HashSet |
no promise | removed |
| unique values, keep order | LinkedHashSet |
insertion order | removed |
| unique values, sorted | TreeSet |
sorted | removed |
Keep that table in your head for this whole article.
12. Remove duplicates from a List
Problem: [1, 2, 3, 2, 4, 1, 5] becomes [1, 2, 3, 4, 5].
Try HashSet first
A Set cannot hold duplicates. So copy the list into a set, then back into a list:
List<Integer> list = List.of(1, 2, 3, 2, 4, 1, 5);
List<Integer> unique = new ArrayList<>(new HashSet<>(list));
System.out.println(unique); // [1, 2, 3, 4, 5]
It looks perfect. But that order is luck. Small integers happen to land in a HashSet in number order. Try different values:
List<Integer> list = List.of(10, 3, 7, 3, 1, 10);
new ArrayList<>(new HashSet<>(list)); // [1, 3, 7, 10] order changed!
new ArrayList<>(new LinkedHashSet<>(list)); // [10, 3, 7, 1] original order kept
A HashSet puts each element in a bucket based on its hash code, and walks the buckets in their own order. It never promises any order. Your code might pass the example in the interview and fail on real data.
Keep the original order with LinkedHashSet
List<Integer> unique = new ArrayList<>(new LinkedHashSet<>(list));
A LinkedHashSet is a HashSet that also keeps a linked list of elements in the order you added them. Same speed for add and contains, a little more memory, and the order is guaranteed.
Say this in the interview: “If order doesn’t matter I’d use a HashSet. Since the expected output keeps the first-seen order, I’ll use a LinkedHashSet.”
Do it by hand
Sometimes the interviewer says “without using a Set’s constructor”. Then loop, and use a set to remember what you’ve seen:
List<Integer> result = new ArrayList<>();
Set<Integer> seen = new HashSet<>();
for (Integer n : list) {
if (seen.add(n)) { // true only the first time
result.add(n);
}
}
Don’t use result.contains(n) instead of the set. contains on a list checks every element, so the whole loop becomes O(n²). With a HashSet, it’s O(n).
And with streams (you’ll meet these properly in Phase 7):
List<Integer> unique = list.stream().distinct().toList(); // keeps order
13. Find common elements between two lists
Problem: A = [1, 2, 3, 4], B = [3, 4, 5, 6]. The common elements are [3, 4].
With retainAll
retainAll keeps only the elements that are also in the other collection, and removes the rest:
List<Integer> a = List.of(1, 2, 3, 4);
List<Integer> b = List.of(3, 4, 5, 6);
Set<Integer> common = new LinkedHashSet<>(a); // a copy, so a is not changed
common.retainAll(new HashSet<>(b));
System.out.println(common); // [3, 4]
Two details matter:
retainAllchanges the collection you call it on. That’s why we copyainto a new set first. Callinga.retainAll(...)on aList.of(...)would throwUnsupportedOperationException, becauseList.oflists can’t be changed.- Pass a
HashSetas the argument.retainAllcallscontainson the argument for every element. On a list, that’s a slow scan each time; on a set, it’s instant.
With a loop and contains
Set<Integer> bSet = new HashSet<>(b);
List<Integer> common = new ArrayList<>();
for (int x : a) {
if (bSet.contains(x)) common.add(x);
}
Same idea, and easy to explain. Cost: O(n + m) time, because building the set is O(m) and each contains is O(1).
Follow-up: “What if the lists have duplicates, like [1, 2, 2, 3] and [2, 2, 4], and you want [2, 2]?” Then a set is wrong, because it would squash the two 2s into one. Count b in a HashMap instead, and decrease the count each time you match. That’s a nice bridge to Phase 4.
14. Find the union of two lists
Problem: the union of [1, 2, 3, 4] and [3, 4, 5, 6] is [1, 2, 3, 4, 5, 6]: everything from both, no repeats.
Set<Integer> union = new LinkedHashSet<>(a);
union.addAll(b);
System.out.println(union); // [1, 2, 3, 4, 5, 6]
addAll adds every element of b. The set quietly ignores the ones it already has.
Compare with adding to a list, which keeps the duplicates:
List<Integer> all = new ArrayList<>(a);
all.addAll(b);
System.out.println(all); // [1, 2, 3, 4, 3, 4, 5, 6]
Same method name, different result, because of the collection’s rules. That’s the whole lesson of this phase in one example.
15. Sort a List
Problem: sort [5, 1, 4, 2, 3], then sort it in reverse.
Collections.sort and list.sort
List<Integer> list = new ArrayList<>(List.of(5, 1, 4, 2, 3));
Collections.sort(list); // [1, 2, 3, 4, 5]
list.sort(null); // same: null means natural order
list.sort(Comparator.naturalOrder()); // same, but clearer
Collections.sort(list) is the old way (Java 1.2). list.sort(...) was added in Java 8 and is the modern way. Since Java 8, Collections.sort simply calls list.sort for you. Both sort in place and both are stable (equal elements keep their order).
Reverse order
Collections.sort(list, Collections.reverseOrder()); // [5, 4, 3, 2, 1]
list.sort(Comparator.reverseOrder()); // [5, 4, 3, 2, 1]
Don’t confuse this with Collections.reverse(list). That just flips the list as it is. It doesn’t sort.
List<Integer> r = new ArrayList<>(List.of(5, 1, 4, 2, 3));
Collections.reverse(r); // [3, 2, 4, 1, 5]: flipped, not sorted
Three traps
1. Immutable lists can’t be sorted.
List.of(5, 1, 4).sort(null); // throws UnsupportedOperationException
Wrap it first: new ArrayList<>(List.of(...)). This one catches people in live coding all the time.
2. Strings sort by character code, so capitals come first.
List<String> names = new ArrayList<>(List.of("ravi", "Asha", "meena", "John"));
Collections.sort(names); // [Asha, John, meena, ravi]
names.sort(String.CASE_INSENSITIVE_ORDER); // ignores case
3. Sorting by something other than the natural order needs a Comparator.
names.sort(Comparator.comparing(String::length)); // shortest name first
That last line is a preview of Phase 5, where Comparators get a whole article.
Cost: Java sorts objects with TimSort: O(n log n) time.
What you practised
ListvsSet: duplicates allowed or notHashSetvsLinkedHashSetvsTreeSet: no order, insertion order, sorted orderretainAllfor the intersection,addAllfor the union, and that both change the collection they’re called onCollections.sort,list.sort,reverseOrder(), and whyCollections.reverseisn’t sortingList.ofis immutable
Next: Phase 4, HashMap interview programs: word counts, the most frequent element and the classic “group anagrams”.
Comments