Java and the Collections Framework

Use Java with ArrayList, HashMap, ArrayDeque and PriorityQueue: a strong choice if your college teaches Java or you target Java backend roles.

Beginner · about 15 hours · difficulty 2/5

Learn first: How Campus and Off-Campus Hiring Works

Java is accepted on every OA platform and is common in service-company interviews. It is verbose but safe, and the Collections Framework covers every structure you need.

The subset you need

  • Primitives vs wrappers: int vs Integer, long for big sums.
  • Collections: ArrayList, HashMap, HashSet, TreeMap, TreeSet (ordered, with floorKey and ceilingKey), ArrayDeque (use it for both stack and queue), PriorityQueue.
  • Sorting: Arrays.sort, Collections.sort, comparators like (a, b) -> a[1] - b[1] or Comparator.comparingInt.
  • StringBuilder for building strings in loops.
  • Fast input with BufferedReader and StringTokenizer instead of Scanner for large inputs.

Pitfalls

  • Comparing Integer objects with == works for small values (cached) and silently fails for larger ones. Use .equals.
  • Comparator a - b can overflow for large values; use Integer.compare(a, b).
  • String concatenation in a loop is O(n^2); use StringBuilder.
  • Arrays.sort on a primitive int[] uses quicksort and can be pushed to O(n^2) by adversarial tests on Codeforces; shuffle first or sort an Integer[].

You are ready to move on when you can use a HashMap for counting, an ArrayDeque as a stack and a PriorityQueue with a custom comparator from memory.

Key concepts

  • Primitives vs wrapper types
  • ArrayList, HashMap, HashSet
  • TreeMap and TreeSet: floor, ceiling, ordered keys
  • ArrayDeque as stack and queue
  • PriorityQueue with comparators
  • StringBuilder
  • Fast I/O with BufferedReader

Other options for this step

  • C++ and the STL: Use C++ with the Standard Template Library: the fastest and most common choice for placements and competitive programming.
  • Python for DSA: Use Python with collections, heapq and bisect: the quickest language to write, fine for interviews but sometimes too slow for strict OAs.

Mini project

Solve 8 warm-ups in Java using only the Collections Framework: word frequency, sort intervals by start, k largest with a PriorityQueue, valid parentheses with ArrayDeque, first unique character, floor lookup with TreeMap, group anagrams and running median with two heaps.

Check yourself

Why might comparing two Integer objects with == pass on small test cases and fail on large ones?

Free resources