SortedMap是有序的,但开发时并不能完全的符合想要的顺序,尤其是当需要按照value值来排序时。最近开发时就碰到了这个问题,解决后总结一下,还有其他方法的话还望赐教。
方法一:
感觉是最简单的一种方法,直接采用Collections 的sort方法,然后复写一下comparator接口,但是要转存到List中进行排序。
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; public class MapSort { public static void main(String args[]) { Map<String, Integer> map = new TreeMap<String, Integer>(); map.put("C", 85); map.put("A", 32); map.put("E", 100); map.put("B", 99); map.put("F", 43); map.put("G", 85); List<Map.Entry<String, Integer>> mapList = new ArrayList<Map.Entry<String, Integer>>( map.entrySet()); Collections.sort(mapList, new Comparator<Map.Entry<String, Integer>>() { public int compare(Map.Entry<String, Integer> num1, Map.Entry<String, Integer> num2) { return num1.getValue().compareTo(num2.getValue()); } }); System.out.println(map); for (Map.Entry<String, Integer> mapping : mapList) { System.out.print(mapping.getKey() + ":" + mapping.getValue() + ", "); } } }
用TreeMap的有序性排序,通过复写comparator来改变他的插入规则。但是改变comparator的时候一定要注意,TreeMap节点的增删改查都会用你复写过的比较器,所以编写比较条件的时候一定要注意考虑全面。我在实现的时候起初就只想要排序,结果发现查找某一个值得时候就会出现存在却找不到的情况,原因是没有返回 0 的情况,所以查找返回值始终为null。
特别注意:我们经常利用map的key值不能重复的特点来去重,所以复写比较器按照value进行比较时,一定要注意插入时value相同的情况。若value值相同则还应该进行key值比较,来判断是否是两条相同的记录,否则会存在map中不能插入value相同但key不相同数据的情况。
import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; public class MapSort1 { public static void main(String[] args) { HashMap<Object, Object> map = new HashMap<Object, Object>(); ValueComparator bvc = new ValueComparator(map); TreeMap<Object, Object> sorted_map = new TreeMap<Object, Object>(bvc); map.put("A", 99); map.put("B", 67); map.put("C", 68); map.put("D", 66); map.put("E", 67); System.out.println("unsorted map: " + map); sorted_map.putAll(map); System.out.println("results: " + sorted_map); System.out.println("a is " + sorted_map.get("A")); } } class ValueComparator implements Comparator<Object> { Map<Object, Object> base; public ValueComparator(Map<Object, Object> base) { this.base = base; } public int compare(Object a, Object b) { int c; if (Integer.parseInt(base.get(a.toString()).toString()) - Integer.parseInt(base.get(b.toString()).toString()) > 0) { c = 1; } else if (Integer.parseInt(base.get(a.toString()).toString()) - Integer.parseInt(base.get(b.toString()).toString()) < 0) { c = -1; } else { // 当相等的时候比较key值,否则value值相同时就会被删除,不会被插入 // map的增删改查都会用到比较器,所以必须得有返回0的情况,表示存在该键值 c = a.toString().compareTo(b.toString()); } return c; } }
利用自己写的排序算法或者其它的排序方法进行数据的排序后,利用LinkedMap保持插入顺序的特性来保持有序。当然实现起来比较麻烦,不推荐,只是一种思路。