Tags: java, live-coding, algorithms, data-structures, streams, collections
Level: intermediate
TL;DR: Essential snippets, core concepts, and common pitfalls for acing Java live coding interviews. Focus on Streams, Collections, and String manipulation efficiency.
String immutability requires using StringBuilder for frequent concatenations to prevent memory overhead.
HashMap and HashSet provide O(1) average time complexity for lookups and insertions.
Java Streams API (java.util.stream) is ideal for concise filtering, mapping, and reducing.
Arrays.sort() uses Dual-Pivot Quicksort for primitives and TimSort for objects.
Use Collections.sort() for sorting lists or pass a custom Comparator for specific ordering.
Always consider edge cases like null inputs, empty collections, and extreme integer values.
Understand the difference between == for reference equality and .equals() for value equality.
PriorityQueue is the standard structure for solving Top-K, Kth largest, or min/max problems.
Q: How do you reverse a string efficiently in Java?R: I use new StringBuilder(str).reverse().toString() because it handles the character array in-place, avoiding multiple string allocations.
Q: How can you iterate over a map's keys and values simultaneously?R: I use a for-each loop on map.entrySet(), which gives me access to both entry.getKey() and entry.getValue() without extra lookups.
Q: What is the difference between an Array and an ArrayList?R: Arrays have a fixed size and can hold primitives. ArrayLists grow dynamically and only hold objects, requiring wrapper classes for primitives.
Modifying a collection while iterating over it using a standard for-each loop, which throws ConcurrentModificationException.
Comparing String values using == instead of .equals().
Forgetting to handle NullPointerException when dealing with uninitialized objects or missing map keys.
Using int for calculations that exceed the 32-bit limit, causing silent overflow.
Overcomplicating simple sorting by writing custom algorithms instead of leveraging Arrays.sort() or Collections.sort().
// Array to List
List<String> list = Arrays.asList(arr);
// List to Array
String[] arr = list.toArray(new String[0]);
// Character frequency map
Map<Character, Integer> freqMap = new HashMap<>();
for (char c : str.toCharArray()) {
freqMap.put(c, freqMap.getOrDefault(c, 0) + 1);
}
// Sort array in reverse order
Arrays.sort(arr, Collections.reverseOrder());
// Using Streams to filter and collect
List<Integer> evens = list.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
// Min Heap (default PriorityQueue behavior)
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
// Max Heap
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
[ ] Practice writing custom Comparators for complex object sorting.
[ ] Review binary search implementation details using Arrays.binarySearch().
[ ] Refresh memory on sliding window and two-pointer algorithm patterns in Java.