import java.util.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class MapUtil {
/**
* 使用 Map按value进行排序(value为String类型)
* @param oriMap
* @return
*/
public static Map<String, String> sortMapByValueStr(Map<String, String> oriMap) {
if (oriMap == null || oriMap.isEmpty()) {
return null;
}
Map<String, String> sortedMap = new LinkedHashMap<String, String>();
List<Map.Entry<String, String>> entryList = new ArrayList<Map.Entry<String, String>>(
oriMap.entrySet());
Collections.sort(entryList, new MapValueComparator());
Iterator<Map.Entry<String, String>> iter = entryList.iterator();
Map.Entry<String, String> tmpEntry = null;
while (iter.hasNext()) {
tmpEntry = iter.next();
sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue());
}
return sortedMap;
}
/**
* 使用 Map按value进行排序 升序(value为Double类型)
* @param map
* @return
*/
public static Map<String, Double> sortMapByValueDob(Map<String, Double> map) {
List<Map.Entry<String, Double>> wordMap = new ArrayList<Map.Entry<String, Double>>(map.entrySet());
// System.out.println(wordMap);
Collections.sort(wordMap, new Comparator<Map.Entry<String, Double>>() {// 根据value排序
public int compare(Map.Entry<String, Double> o1, Map.Entry<String, Double> o2) {
double result = o1.getValue() - o2.getValue();//升序降序交换位置即可
if (result > 0)
return 1;
else if (result == 0)
return 0;
else
return -1;
}
});
System.out.println("------------map按照value升序排序--------------------");
Map<String, Double> ma = new LinkedHashMap<String, Double>();
for (Map.Entry<String, Double> entry : wordMap) {
// System.out.println(entry.getKey() + "->" + entry.getValue());
ma.put(entry.getKey(),entry.getValue());
}
return ma;
}
/**
* 使用 Map按value进行排序 降序(value为Double类型)
* @param map
* @return
*/
public static Map<String, Double> sortMapByValueDobDown(Map<String, Double> map) {
List<Map.Entry<String, Double>> wordMap = new ArrayList<Map.Entry<String, Double>>(map.entrySet());
// System.out.println(wordMap);
Collections.sort(wordMap, new Comparator<Map.Entry<String, Double>>() {// 根据value排序
public int compare(Map.Entry<String, Double> o1, Map.Entry<String, Double> o2) {
double result = o2.getValue() - o1.getValue();//升序降序交换位置即可
if (result > 0)
return 1;
else if (result == 0)
return 0;
else
return -1;
}
});
System.out.println("------------map按照value降序排序--------------------");
Map<String, Double> ma = new LinkedHashMap<String, Double>();
for (Map.Entry<String, Double> entry : wordMap) {
// System.out.println(entry.getKey() + "->" + entry.getValue());
ma.put(entry.getKey(),entry.getValue());
}
return ma;
}
}