Sorting HashMap by Keys using TreeMap and Comparator
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import com.kanth.bo.Employee;
public class HashMapSortKeys {
public static void main(String[] args) {
Map<String, Employee> unsortedMap = getEmpData();
Map<String, Employee> treeMap = new TreeMap<String, Employee>(new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return Integer.parseInt(s1) > Integer.parseInt(s2) ? 1 : -1;
}
});
unsortedMap.forEach((k, v) -> {
treeMap.put(k, v);
});
System.out.println("after sorting " + treeMap.size());
treeMap.forEach((k, v) -> {
System.out.println("key is " + k + "Value is " + v);
});
}
public static Map<String, Employee> getEmpData() {
String proj1[] = { "Singtel", "Ericson", "STC", "TM" };
String proj2[] = { "Singtel", "Cisco", "STC", "TM" };
String proj3[] = { "STC", "TM" };
Map<String, Employee> empData = new HashMap<>();
empData.put("1234", new Employee("Ramakanth", 31000d, "SMP", 27, proj1));
empData.put("112", new Employee("Sanjay", 40000d, "IOT", 27, proj1));
empData.put("578", new Employee("Anil", 50000d, "SMP", 28, proj3));
empData.put("889", new Employee("Raju", 30000d, "SMP", 27, proj2));
empData.put("762", new Employee("Vijay", 20000d, "IOT", 32, proj1));
empData.put("687", new Employee("Eswar", 27000d, "SMP", 30, proj2));
empData.put("579", new Employee("Satish", 21000d, "ADP", 26, proj3));
return empData;
}
}
class Employee {
private String name;
private Double salary;
private String Dept;
private Integer age;
private String[] projects;
//getters and setters
}
0 comments:
Post a Comment