Sort the HashMap by Values using comperator and Entry Object
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import java.util.Set;
import com.kanth.bo.Employee;
public class HashMapSortByValues {
public static void main(String[] args) {
Map<String, Employee> unsortedMap = getEmpData();
Set<Entry<String, Employee>> dataset = unsortedMap.entrySet();
List<Entry<String, Employee>> mylist = new ArrayList<>(dataset);
//Comparator for sorting by salary for Employee Object
Comparator<Entry<String, Employee>> myvalucomp = new Comparator<Entry<String, Employee>>() {
@Override
public int compare(Entry<String, Employee> o1, Entry<String, Employee> o2) {
return o1.getValue().getSalary() < o2.getValue().getSalary() ? 1 : -1;
}
};
//sorting based on comparator
Collections.sort(mylist, myvalucomp);
//LinkedHashMap -- as it maintains the order
Map<String, Employee> sortedMap = new LinkedHashMap<>();
sortedMap = mylist.stream()
.collect(Collectors.toMap(Entry::getKey, Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
// sorted by values
sortedMap.forEach((k, v) -> {
System.out.println("The key is " + k + " values " + 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