Given example shows how to sort user defined objects TreeMap, you can sort the keys based on the logic provided inside the method.
Given a record of employees name and salary as positive integer, it is required to sort the records on the basis of employee salary, using TreeMap in Java. If salary is same, then use employee name for comparison.
Input : xbnnskd 100 geek 50 Output : geek 50 xbnnskd 100 Input : shyam 50 ram 50 Output : ram 50 shyam 50 Explanation : As both the employees have equal pay, sorting is done on the basis of employee's name.
1. Traverse through the string and map the employee's salary(S) with the list of employee names having salary S. 2. Use a TreeMap to have keys(Employee's Salary) in a sorted manner. 3. Now, Traverse through the map and print the sorted records.
Below is the implementation of above approach:
Neha 20 Karan 50 Harsh 100 Neha 100 Samay 600
Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.
- Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
- Java.util.TreeMap.firstEntry() and firstKey() in Java
- Java.util.TreeMap.containskey() and containsValue() in Java
- Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
- Java.util.TreeMap.put() and putAll() in Java
- Java.util.TreeMap.floorEntry() and floorKey() in Java
- HashMap and TreeMap in Java
- Differences between TreeMap, HashMap and LinkedHashMap in Java
- TreeMap ceilingKey() in Java with Examples
- TreeMap ceilingEntry() and ceilingKey() methods in Java
- TreeMap containsValue() Method in Java
- TreeMap size() Method in Java
- TreeMap get() Method in Java
- TreeMap clone() Method in Java
- TreeMap containsKey() Method in Java
- TreeMap clear() Method in Java
- TreeMap in Java
- TreeMap headMap() Method in Java
- TreeMap entrySet() Method in Java
- TreeMap keySet() Method in Java
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.