package miaosu.utils;
import java.util.*;
//对map进行排序
public class MapUtils {
// Map的value值降序排序
public static <K, V extends Comparable<? super V>> Map<K, V> sortDescend(Map<K, V> map) {
List<Map.Entry<K, V>> list = new ArrayList<>(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
@Override
public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
int compare = (o1.getValue()).compareTo(o2.getValue());
return -compare;
}
});
Map<K, V> returnMap = new LinkedHashMap<K, V>();
for (Map.Entry<K, V> entry : list) {
returnMap.put(entry.getKey(), entry.getValue());
}
return returnMap;
}
// Map的value值升序排序
public static <K, V extends Comparable<? super V>> Map<K, V> sortAscend(Map<K, V> map) {
List<Map.Entry<K, V>> list = new ArrayList<Map.Entry<K, V>>(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
@Override
public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
int compare = (o1.getValue()).compareTo(o2.getValue());
return compare;
}
});
Map<K, V> returnMap = new LinkedHashMap<K, V>();
for (Map.Entry<K, V> entry : list) {
returnMap.put(entry.getKey(), entry.getValue());
}
return returnMap;
}
//对map排序并取出前n个
public static Map<String, Double> sortMapByValue(Map<String, Double> map,Integer num) {
Map<String, Double> sortedMap = new LinkedHashMap<String, Double>();
List<Map.Entry<String,Double>>lists=new ArrayList<Map.Entry<String,Double>>(map.entrySet());
Collections.sort(lists,new Comparator<Map.Entry<String, Double>>() {
public int compare(Map.Entry<String, Double> o1,Map.Entry<String, Double> o2)
{
double q1=o1.getValue();
double q2=o2.getValue();
double p=q2-q1;
if(p>0){
return 1;
}
else if(p==0){
return 0;
}
else
return -1;
}
});
if(lists.size()>=num){
//lists.subList()用法
for(Map.Entry<String, Double> set:lists.subList(0, num)){
sortedMap.put(set.getKey(), set.getValue());
}
}else {
for(Map.Entry<String, Double> set:lists){
sortedMap.put(set.getKey(), set.getValue());
}
}
return sortedMap;
}
}
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交