为了对HashMap中的value进行排序,写了一个公共方法
传入HashMap<自定义,自定义>即可,下列代码中是实例化为HashMap的Map<String,String>
/* * 对Map<String,String>中的value进行排序(正序) */ public Map<String, String> sortMapByValue(Map<String, String> unSortMap) { if (unSortMap == null || unSortMap.isEmpty()) { return null; } List<Map.Entry<String, String>> listEntry = new ArrayList<>(); listEntry.addAll(unSortMap.entrySet()); Collections.sort(listEntry, new Comparator<Map.Entry<String, String>>() { @Override public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) { // String的compareTo方法,返回负数,说明o1在o2的字典顺序之前。 return o1.getValue().compareTo(o2.getValue());// 此处。getValue改成getKey即可对Map按照key进行排序 } }); Map<String,String> sortedMap = new LinkedHashMap<>(); for(Map.Entry<String, String> entry : listEntry){ sortedMap.put(entry.getKey(), entry.getValue()); } return sortedMap; }
对HashMap中的key进行排序,只需按注释修改getValue为getKey即可修改。