Most Java coding questions come down to picking the right collection. Ask two questions: do I need order, and do I need duplicates?
import java.util.*;
public class CollectionsDemo {
public static void main(String[] args) {
List<String> subjects = new ArrayList<>(List.of("DBMS", "OS", "CN", "OS"));
Set<String> unique = new LinkedHashSet<>(subjects);
Map<String, Integer> credits = new TreeMap<>();
credits.put("OS", 4); credits.put("DBMS", 4); credits.put("CN", 3);
Deque<String> history = new ArrayDeque<>();
history.push("page1"); history.push("page2");
Queue<Integer> pq = new PriorityQueue<>(List.of(30, 10, 20));
System.out.println(subjects + " " + unique);
System.out.println(credits);
System.out.println(history.pop() + " " + pq.poll());
}
}[DBMS, OS, CN, OS] [DBMS, OS, CN]
{CN=3, DBMS=4, OS=4}
page2 10Quick chooser
- ArrayList: an ordered list with duplicates. Get by index is O(1); adding at the end is O(1) on average; inserting or removing in the middle is O(n). Your default list.
- HashSet / LinkedHashSet: no duplicates, contains() is O(1) on average. LinkedHashSet also keeps insertion order, as above.
- HashMap: key to value, O(1) average lookups. Iteration order is not guaranteed, so never print a HashMap and expect a fixed order.
- TreeMap / TreeSet: kept sorted by key, O(log n) operations, plus firstKey, floorKey and ceilingKey for range questions.
- ArrayDeque: use it as a stack (push/pop) or a queue (offer/poll). It is faster than the old Stack class and than LinkedList.
- PriorityQueue: always gives you the smallest element first (a min-heap). Pass Comparator.reverseOrder() for a max-heap. Ideal for "top k" questions.
Habits that save marks
- Declare with the interface (List, Map) and create with the class (ArrayList, HashMap), so you can switch later.
- List.of and Map.of create collections that cannot be changed. Wrap them in new ArrayList<>(...) if you need to add items.
- Do not remove items from a list inside a for-each loop over it; you will get a ConcurrentModificationException. Use removeIf instead.
- Practise more in UniCircle interview prep: Java.
#java#collections#hashmap#data structures
Sources and further reading
Written by the UniCircle team, checked by an editor on 22 Oct 2026. It is not official policy of any university. Exam patterns and rules change; confirm dates and rules on the official website.
