Interviewer question in one of my interviews.
We have
Employee
class withid
,firstName
, andlastName
fields and getters and setters of these fields. We do not have source code of this class, it is in JAR. We are usingEmployee
instances as the key inTreeMap
. Now we want to sort thisTreeMap
based on theEmployee
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:
Employee
and have the derived class implement Comparable<...>
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.