Java Comparator — Java Technical Interview Questions & Answers
Java Comparator
Java Comparator
- Comparator belongs to the Collections story. List = ordered, duplicates OK (ArrayList). Set = unique (HashSet). Map = key → value (HashMap). Pick by need, not by what you revised last.
- For Comparator: ArrayList is the daily List: get(i) is fast, add at end is fast. HashMap lookup by key is average O(1). HashSet is unique values, no duplicates.
- Use Comparator with generics: List<String>, Map<String, Integer>. Iterate with for-each or iterator. Don’t use a raw array when the size must grow.
- Let's take this on the board with one tiny Main class — no extra files. Java Comparator — sort uses String's natural compare (case-insensitive here). Start from main, go line by line, and stop at each print. That output is the proof for Comparator.
Technical Interview Tip: One class, many Comparators — that's the power.
Code Examples for Java Comparator
Example
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> names = Arrays.asList("Ravi", "Asha", "Neha");
names = new ArrayList<>(names);
names.sort(String::compareToIgnoreCase);
System.out.println(names);
}
}Java Comparator — sort uses String's natural compare (case-insensitive here).
How to Explain Java Comparator to an Interviewer
What is Comparator?
Comparator — List = order + duplicates OK. Set = unique. Map = key → value. Comparator — pick it only when that structure matches the problem. Comparator — generics List<String>. ArrayList for daily lists. HashMap for lookup.
Why do we use Comparator in Java?
Makes the program clearer or safer Comparator — List = order + duplicates OK. Set = unique. Map = key → value.
Write one small example of Comparator.
Show syntax Say what prints
What mistake do beginners make with Comparator?
Only the name, no example Comparator — using arrays for everything that must grow, or mixing List/Set/Map.
Where is Comparator used in a real program?
Day-to-day Java code