WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Java Collections · Advanced · question 59 of 100

How do you implement a custom Comparator in Java Collections, and what are some use cases for doing so?

📕 Buy this interview preparation book: 100 Java Collections questions & answers — PDF + EPUB for $5

In Java Collections, the Comparator interface is used to define a custom ordering for objects. This is useful when the natural ordering of objects does not meet the requirements of a particular application, or when objects of different classes need to be compared.

To implement a custom Comparator, we need to create a class that implements the Comparator interface and provides an implementation of the compare method. The compare method takes two objects as input and returns an integer value that indicates their relative ordering. If the first object should come before the second object, a negative value is returned; if the first object should come after the second object, a positive value is returned; and if the two objects are equal in terms of ordering, a zero value is returned.

Here is an example implementation of a custom Comparator that orders strings in reverse alphabetical order:

import java.util.Comparator;

public class ReverseStringComparator implements Comparator<String> {
    @Override
    public int compare(String s1, String s2) {
        return s2.compareTo(s1);
    }
}

In this example, the compare method simply calls the compareTo method of the second string with the first string as input, which has the effect of reversing the natural ordering of the strings.

To use this custom Comparator, we can pass an instance of the ReverseStringComparator class to any method that takes a Comparator as an argument. For example, to sort a list of strings in reverse alphabetical order, we can use the Collections.sort method:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Example {
    public static void main(String[] args) {
        List<String> strings = new ArrayList<>();
        strings.add("foo");
        strings.add("bar");
        strings.add("baz");

        Comparator<String> comparator = new ReverseStringComparator();
        Collections.sort(strings, comparator);

        System.out.println(strings);
    }
}

In this example, we create a list of strings, then create an instance of the ReverseStringComparator class and pass it to the Collections.sort method along with the list of strings. The sort method uses the compare method of the ReverseStringComparator class to determine the ordering of the strings, resulting in a sorted list of strings in reverse alphabetical order.

Some use cases for implementing a custom Comparator include sorting objects by non-natural attributes, such as size, weight, or date, or sorting objects of different classes in a unified way. For example, we might have a list of shapes that includes both circles and squares, and we might want to sort them by area rather than by shape. In this case, we could implement a custom Comparator that calculates the area of each shape and uses that value to determine the ordering.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Java Collections interview — then scores it.
📞 Practice Java Collections — free 15 min
📕 Buy this interview preparation book: 100 Java Collections questions & answers — PDF + EPUB for $5

All 100 Java Collections questions · All topics