Sort HashMap basis on Object's member variable from value
本问题已经有最佳答案,请猛点这里访问。
上一节课
1 2 3 4 |
以及一个包含该对象的值的映射
现在我想把
提前谢谢
使用此构造函数将treemap与自定义比较器一起使用:
http://DOCS.Oracle .COM/JavaSe/ 6 /DOCS/API/Java/UTL/TeReMAP.html
不能对
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | 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); } } |
排序之后,您可以将条目放回支持排序的映射中,例如LinkedHashMap。
这取决于您的用例:如果您需要始终对映射进行排序,那么使用带有额外开销的
米莎?L提出了一个链接,它是一个映射"键","值"按值(Java)排序。我做了些改变。它对我有用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | 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; } } |
有关解决方案,请参考上述维度链接。
感谢所有回复的人。