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
    You can use Comparator. – Eran May 02 '18 at 06:58
  • 1
    Why would source code be relevant at all? – lexicore May 02 '18 at 07:00
  • 2
    Use Comparator, e.g https://stackoverflow.com/questions/18720800/sorting-map-using-comparator – sashwat May 02 '18 at 07:00
  • 4
    @lexicore The fact that you don't have source code prevents you from making the class implement [`Comparable`](https://docs.oracle.com/javase/10/docs/api/java/lang/Comparable.html). They want the alternative, i.e. for answer to be that you can give a [**`Comparator`**](https://docs.oracle.com/javase/10/docs/api/java/util/Comparator.html) on the [`TreeMap` constructor](https://docs.oracle.com/javase/10/docs/api/java/util/TreeMap.html#%3Cinit%3E(java.util.Comparator)). It's a test to see how familiar you are with `TreeMap`, one of the more common classes in the Java Runtime Library. – Andreas May 02 '18 at 07:02
  • Possible duplicate of [Sorting Map using Comparator](https://stackoverflow.com/questions/18720800/sorting-map-using-comparator) – contrapost May 02 '18 at 07:10
  • @Andreas You can't make third-party class implement `Comparable` independent of whether source code is available or not. So I still don't see how source code availability is relevant. – lexicore May 02 '18 at 08:23
  • @contrapost Of course it is a duplicate but only for those who already know :) If anyone does not know about the existence of the `Comparator` the question is *different*. It should stay here. – Honza Zidek May 02 '18 at 08:40

2 Answers2

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)

vincrichaud
  • 2,218
  • 17
  • 34
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.

SeverityOne
  • 2,476
  • 12
  • 25