Using TreeMap to sort User-defined Objects in Java
Last Updated :
11 Dec, 2018
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.
Examples:
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.
Approach:
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:
import java.io.*;
import java.util.*;
public class GFG {
static void sortRecords(String records)
{
String[] rec = records.split( " " );
Map<Integer, ArrayList<String> > map = new TreeMap<>();
for ( int i = 1 ; i < rec.length; i += 2 ) {
int sal = Integer.parseInt(rec[i]);
String name = rec[i - 1 ];
if (map.containsKey(sal)) {
ArrayList<String> al = map.get(sal);
al.add(name);
Collections.sort(al);
map.remove(sal);
map.put(sal, al);
}
else {
ArrayList<String> al = new ArrayList<>();
al.add(name);
map.put(sal, al);
}
}
for (Map.Entry<Integer,
ArrayList<String> >
entry : map.entrySet()) {
ArrayList<String> al1 = entry.getValue();
for ( int i = 0 ; i < al1.size(); i++)
System.out.print(al1.get(i) + " "
+ entry.getKey() + " " );
}
}
public static void main(String args[])
{
String records = "Harsh 100 Neha 100 Neha 20 Samay 600 Karan 50" ;
sortRecords(records);
}
}
|
Output:
Neha 20 Karan 50 Harsh 100 Neha 100 Samay 600
Share your thoughts in the comments
Please Login to comment...