Map根据key排序
1.第一种方法
首先定义好一个传key的比较器对象来构造TreeMap
Map<String,Object> mapping = new TreeMap<>(new MyComparator());
mapping.put("afieldName","特征名称");
mapping.put("std","方差");
mapping.put("min","最小值");
mapping.put("avg","平均值");
mapping.put("nanCount","缺失值");
mapping.put("max","最大值");
mapping.put("skewness","偏度");
mapping.put("kurtosis","峰度");
mapping.put("standardDeviation","标准差");
System.out.println("mapping="+mapping);
定义key的比较器
class MyComparator implements Comparator<String> {
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
}
1.第二种方法
Map先存放数据,之后再进行排序
Map根据key的值进行排序
/**
* Map根据key的值进行排序
*
* @param map
* @return
*/
public static Map<String,Object> sortMapByKey(Map<String,Object> map){
List<Map.Entry<String,Object>> entryList = new ArrayList<>(map.entrySet());
entryList.sort(Comparator.comparing(o-> o.getKey()));
//遍历排序好的list,一定要放进LinkedHashMap,因为只有LinkedHashMap是根据插入顺序进行存储
LinkedHashMap<String,Object> linkedHashMap = new LinkedHashMap<>();
for(Map.Entry<String,Object> entry : entryList){
linkedHashMap.put(entry.getKey(),entry.getValue());
}
return linkedHashMap;
}
Map根据value的值进行排序
/**
* Map根据value的值进行排序
*
* @param map
* @return
*/
public static Map<String,Object> sortMapByValue(Map<String,Object> map){
List<Map.Entry<String,Object>> entryList = new ArrayList<>(map.entrySet());
entryList.sort(Comparator.comparing(o-> o.getValue().toString()));
//遍历排序好的list,一定要放进LinkedHashMap,因为只有LinkedHashMap是根据插入顺序进行存储
LinkedHashMap<String,Object> linkedHashMap = new LinkedHashMap<>();
for(Map.Entry<String,Object> entry : entryList){
linkedHashMap.put(entry.getKey(),entry.getValue());
}
return linkedHashMap;
}
进行代码测试
定义Map测试
public static void main(String[] args) {
//传进来一个key的比较器对象来构造treemap
Map<String,Object> mapping = new TreeMap<>();
mapping.put("fieldName","特征名称");
mapping.put("std","方差");
mapping.put("min","最小值");
mapping.put("avg","平均值");
mapping.put("nanCount","缺失值");
mapping.put("max","最大值");
mapping.put("skewness","偏度");
mapping.put("kurtosis","峰度");
mapping.put("standardDeviation","标准差");
System.out.println("-------------1-------------");
//按key排序
Map<String,Object> objectMapKey = sortMapByKey(mapping);
System.out.println(objectMapKey);
System.out.println("-------------2-------------");
//按value排序
Map<String,Object> objectMap = sortMapByValue(mapping);
System.out.println(objectMap);
}