Using Custom Sorting
- Create a new class called
Employee
:
class Employee implements Comparable<Employee> {
private int id;
private String name;
public Employee(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
@Override
public int compareTo(Employee e) {
return this.id - e.getId();
}
}
- Add some Employees to the TreeMap:
Map<Employee, String> employeeMap = new TreeMap<>();
employeeMap.put(new Employee(3, "John"), "IT");
employeeMap.put(new Employee(2, "Mary"), "HR");
employeeMap.put(new Employee(1, "Peter"), "Finance");
- Now when you iterate through the TreeMap, it will be sorted based on the employee ID:
for(Map.Entry<Employee, String> entry : employeeMap.entrySet()) {
System.out.println(entry.getKey().getId() + " "
+ entry.getKey().getName() + " "
+ entry.getValue());
}