按值按字母顺序排序HashMap
我有一个HashMap
,其中Object是Student的ID,Student是Student的一个对象。
如何通过学生姓名, student->getName()
求助HashMap?
HashMaps本质上是无序的,无法排序。
相反,您可以使用SortedMap实现,例如TreeMap 。
但是,即使是已排序的地图也只能按其键排序。
如果要按值排序,则需要将它们复制到排序列表中。
您可能无法对HashMap进行排序,但您当然可以执行提供相同效果的操作。 我可以使用在Javarevisited博客上发布的优秀代码,通过Integer的降序值对我的HashMap
/* * Java method to sort Map in Java by value eg HashMap or Hashtable * throw NullPointerException if Map contains null values * It also sort values even if they are duplicates */ public static Map sortByValues(Map map){ List> entries = new LinkedList>(map.entrySet()); Collections.sort(entries, new Comparator>() { @Override public int compare(Entry o1, Entry o2) { return o1.getValue().compareTo(o2.getValue()); // to compare alphabetically case insensitive return this instead // o1.getValue().toString().compareToIgnoreCase(o2.getValue().toString()); } }); //LinkedHashMap will keep the keys in the order they are inserted //which is currently sorted on natural ordering Map sortedMap = new LinkedHashMap(); for(Map.Entry entry: entries){ sortedMap.put(entry.getKey(), entry.getValue()); } return sortedMap; }
要调用此方法,我使用:
Map sorted = sortByValues(myOriginalHashMapObject);
阅读更多: http : //javarevisited.blogspot.com/2012/12/how-to-sort-hashmap-java-by-key-and-value.html#ixzz2akXStsGj
地图不能按值排序。 但是你可以这样做:
Collection students = map.values(); Collection.sort(new ArrayList (students)), new Comparator () { public int compare(Student s1, Student s2) { return s1.getName().compareTo(s2.getName()); } });
当然,假设您需要迭代值。 (为什么还要这样订购?)
祝你好运。
HashMaps无法按其值排序。 Map是基于密钥的恒定时间查找而设计的,因此不需要按值排序。 如果需要按名称排序,我建议使用SortedSet
并创建一个按名称排序的比较器。
class StudentComparator implements Comparator { int compare(Student s1, Student s2) { return s1.getName().compareTo(s2.getName()); } }
如果您需要一个恒定时间查找和一个按值排序的集合,那么您可能需要维护一个映射和一个集合。
我肯定会使用一个新类来存储密钥和对象。
然后你可以将Map的每个元素放到这个类的forms的ArrayList中,最后使用比较器对ArrayList进行排序,之后你只需构建一个新的Map。 代码将是这样的:
Map
PairValue类
class PairValue { private Object value; private Student student; public PairValue(Object value, String student) { this.value = value; this.student= student; } public String getValue() { return value; } public String getStudent() { return student; } }
这就是我解决过去类似问题的方式。 请注意,返回的地图实现需要是LinkedHashMap。