WalzoneInterview Prep
πŸ“ž Interviewing soon? Practice with a realistic AI mock phone interview β€” it calls you, then scores you. First 15 min FREE β†’

Java Collections Β· Expert Β· question 74 of 100

How does the Comparator interface work in Java Collections, and what are some use cases for implementing it?

πŸ“• Buy this interview preparation book: 100 Java Collections questions & answers β€” PDF + EPUB for $5

The Comparator interface is used to provide a custom ordering of elements in a collection. It is part of the Java Collections Framework and is used to sort objects based on a specific ordering. The Comparator interface contains a single method called compare() which is used to compare two objects.

The compare() method takes two arguments, which are the objects to be compared. The method returns an integer value indicating the relative order of the objects. The returned integer value can be interpreted as follows:

A negative integer: if the first object is less than the second object. Zero: if the two objects are equal. A positive integer: if the first object is greater than the second object.

Here is an example implementation of a Comparator that sorts a list of Person objects by their age:

import java.util.Comparator;

public class PersonAgeComparator implements Comparator<Person> {
    @Override
    public int compare(Person p1, Person p2) {
        return p1.getAge() - p2.getAge();
    }
}

In the above code, PersonAgeComparator is a custom implementation of the Comparator interface. It sorts Person objects based on their age. The compare() method subtracts the age of the second person from the age of the first person, returning a negative value if the first person is younger, a positive value if the first person is older, and zero if they are the same age.

The Comparator interface is commonly used in sorting collections such as List and TreeMap. It allows for custom sorting of objects, which may not be possible with the natural ordering of objects provided by the Comparable interface.

Some use cases for implementing the Comparator interface include sorting lists of objects by a custom property, sorting objects in a custom order, and sorting objects based on complex criteria that cannot be represented by the natural ordering of objects.

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