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:
intvsInteger,longfor big sums. - Collections:
ArrayList,HashMap,HashSet,TreeMap,TreeSet(ordered, withfloorKeyandceilingKey),ArrayDeque(use it for both stack and queue),PriorityQueue. - Sorting:
Arrays.sort,Collections.sort, comparators like(a, b) -> a[1] - b[1]orComparator.comparingInt. StringBuilderfor building strings in loops.- Fast input with
BufferedReaderandStringTokenizerinstead ofScannerfor large inputs.
Pitfalls
- Comparing
Integerobjects with==works for small values (cached) and silently fails for larger ones. Use.equals. - Comparator
a - bcan overflow for large values; useInteger.compare(a, b). Stringconcatenation in a loop is O(n^2); useStringBuilder.Arrays.sorton a primitiveint[]uses quicksort and can be pushed to O(n^2) by adversarial tests on Codeforces; shuffle first or sort anInteger[].
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
- Oracle Java Tutorials: Collections (Oracle)
- Java SE API documentation (Oracle)
- GeeksforGeeks (GeeksforGeeks)