简体   繁体   中英

Sorting without Class source code

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?

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 )

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM