0

Interviewer question in one of my interviews.

We have Employee class with id, firstName, and lastName fields and getters and setters of these fields. We do not have source code of this class, it is in JAR. We are using Employee instances as the key in TreeMap. Now we want to sort this TreeMap based on the Employee id field.

I know we can use Comparable interface to sort but how can we use it if we do not have the source code?

7
  • 7
    You can use Comparator. Commented May 2, 2018 at 6:58
  • 1
    Why would source code be relevant at all? Commented May 2, 2018 at 7:00
  • 2
    Use Comparator, e.g stackoverflow.com/questions/18720800/… Commented May 2, 2018 at 7:00
  • 4
    @lexicore The fact that you don't have source code prevents you from making the class implement Comparable. They want the alternative, i.e. for answer to be that you can give a Comparator on the TreeMap constructor. It's a test to see how familiar you are with TreeMap, one of the more common classes in the Java Runtime Library. Commented May 2, 2018 at 7:02
  • Possible duplicate of Sorting Map using Comparator Commented May 2, 2018 at 7:10

2 Answers 2

0

Based on Andreas comment :

Since you does not have the source code, you can't use the interface comparable. And that's the goal of your interviewer to make you use an alternative. This alternative is to use a Comparator.

I'll let you search how to use it (here an example)

Sign up to request clarification or add additional context in comments.

Comments

0

You have two options:

  1. Subclass Employee and have the derived class implement Comparable<...>
  2. Write a Comparator<Employee> and pass it as a parameter to the constructor of TreeMap

The first one is more trouble than it's worth, because you're dealing with a different class. So let's see about using a Comparator.

final Comparator<Employee> employeeComparator = Comparator
        .comparing(Employee::getLastName)
        .thenComparing(Employee::getFirstName);
final SortedMap<Employee, String> map = new TreeMap<>(employeeComparator);

This defines the comparator as a Java 8 lambda that first compares the last name and then the first name.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.