Sort HashMap basis on Object's member variable from value
Solution 1
Michaël suggested one link which is Sort a Map<Key, Value> by values (Java) . I did some change in it. and it works for me
class ValueComparator implements Comparator<Integer> {
Map<Integer, Employee> base;
public ValueComparator(Map<Integer, Employee> base) {
this.base = base;
}
// Note: this comparator imposes orderings that are inconsistent with equals.
public int compare(Integer a, Integer b) {
return ((Employee)base.get(a)).compareTo(base.get(b));
}
}
class Employee implements Comparable {
public String name;
public int id;
Employee(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public int compareTo(Object obj) {
return this.name.compareTo(((Employee)obj).name);
}
public String toString() {
return name;
}
}
For solution please refere above mension link too.
Thanks for all who have reply.
Solution 2
You can't sort a HashMap
, but you can sort its entries obtained with entrySet()
.
public class MapSort {
private static class Employee {
public String name;
public Employee(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
public static void main(String[] args) {
Map<Integer, Employee> map = new HashMap<Integer, Employee>();
map.put(1, new MapSort.Employee("x"));
map.put(2, new MapSort.Employee("a"));
map.put(3, new MapSort.Employee("f"));
List<Map.Entry<Integer, Employee>> entryList = new ArrayList<Map.Entry<Integer, Employee>>(map.entrySet());
Collections.sort(
entryList, new Comparator<Map.Entry<Integer, Employee>>() {
@Override
public int compare(Map.Entry<Integer, Employee> integerEmployeeEntry,
Map.Entry<Integer, Employee> integerEmployeeEntry2) {
return integerEmployeeEntry.getValue().name
.compareTo(integerEmployeeEntry2.getValue().name);
}
}
);
System.out.println(entryList);
}
}
After sorting you can put back your entries in a map that supports ordering, for example LinkedHashMap.
It depends on your use case: if you need to keep the map always sorted it's simpler to employ a TreeMap
that comes with an additional overhead. If you need just an one time sorting, you can use a HashMap
with the above code.
Solution 3
Use a TreeMap with a custom Comparator using this constructor:
http://docs.oracle.com/javase/6/docs/api/java/util/TreeMap.html#TreeMap(java.util.Comparator)
Navnath
Updated on July 09, 2022Comments
-
Navnath almost 2 years
Have one class
class Employee { int id; String name; }
and one map which contains this object in value
Map<Integer, Employee> map = new HashMap<Integer, Employee>();
Now I want to sort above
map
one the basis ofEmployee's name
. Means when I iterate this map usingMap.Entry
,Employee
objects must retrive alphabetically.Thanks in advance