Java-Java中根据Value对Map排序
根据Value值对Map排序
Map<K,V>中的V对象实现了comparable接口可比较,示例如下:
实现了comparable接口的对象V
public class Music implements Comparable<Music>,Serializable{
…………
public int compareTo(Music o) {
int i = o.getPeakTime().compareTo(this.getPeakTime()); //倒序
if(i==0){
i = o.getNum().compareTo(this.getNum());
if(i == 0){
i = o.getNeid().compareTo(this.getNeid());
}
}
return i;
}
…………
}
排序
排序的方法
public class MapUtil {
…………
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue( Map<K, V> map ){
List<Map.Entry<K, V>> list =
new LinkedList<Map.Entry<K, V>>( map.entrySet() );
Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
int res = o1.getValue().compareTo(o2.getValue());
return res != 0 ? res : 1; // 处理当value相等时,不丢失元素
}
});
Map<K, V> result = new LinkedHashMap<K, V>();
for (Map.Entry<K, V> entry : list){
result.put( entry.getKey(), entry.getValue() );
}
return result;
}
…………
public static <K,V extends Comparable<? super V>> SortedSet<Map.Entry<K,V>> entriesSortedByValues(Map<K,V> map) {
SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<Map.Entry<K,V>>(
new Comparator<Map.Entry<K,V>>() {
@Override public int compare(Map.Entry<K,V> e1, Map.Entry<K,V> e2) {
int res = e1.getValue().compareTo(e2.getValue());
return res != 0 ? res : 1; // Special fix to preserve items with equal values
}
}
);
sortedEntries.addAll(map.entrySet());
return sortedEntries;
}
…………
public static void main(String[] args){
Map<String, Music> nonSortedMap = new HashMap<String, Music>();
…………
// nonSortedMap.put("aaa", 1);
// nonSortedMap.put("ddd", 3);
// nonSortedMap.put("ccc", 1);
// nonSortedMap.put("rrrr", 2);
Map<String,Music> sortedMap = MapUtil.sortByValue(nonSortedMap);
for(Map.Entry<String,Music> entry : sortedMap.entrySet()){
System.out.println(entry.getKey()+":"+entry.getValue());
}
// for (Map.Entry<String, Integer> entry : entriesSortedByValues(nonSortedMap)) {
// System.out.println(entry.getKey()+":"+entry.getValue());
// }
}
}
使用TreeMap<K,V>实现对Map<K,V>排序
TreeMap中,是实现了对key的排序,不能根据value的大小来排序,其中的K,必须实现一个可比较的接口。
1. TreepMap通过传入比较器的构造方法
public TreeMap(Comparator<? super K> comparator) {
this.comparator = comparator;
}
2.也可以通过comparator()方法传入
public Comparator<? super K> comparator() {
return comparator;
}
3.在向TreeMap中put元素时实现了根据key来排序
public V put(K key, V value) {
…………
// split comparator and comparable paths
Comparator<? super K> cpr = comparator;
if (cpr != null) {
do {
parent = t;
cmp = cpr.compare(key, t.key);
if (cmp < 0)
t = t.left;
else if (cmp > 0)
t = t.right;
else
return t.setValue(value);
} while (t != null);
}
else {
if (key == null)
throw new NullPointerException();
Comparable<? super K> k = (Comparable<? super K>) key;
do {
parent = t;
cmp = k.compareTo(t.key);
if (cmp < 0)
t = t.left;
else if (cmp > 0)
t = t.right;
else
return t.setValue(value);
} while (t != null);
}
…………
}