一,MapUtil
package com.util;import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.Iterator;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.Map.Entry;public class MapUtil { /** * 对map排序。 */ public static Map<String, Double> sortMapByValue(Map<String, Double> oriMap) { Map<String, Double> sortedMap = new LinkedHashMap<String, Double>(); if (oriMap != null && !oriMap.isEmpty()) { List<Map.Entry<String, Double>> entryList = new ArrayList<Map.Entry<String, Double>>(oriMap.entrySet()); Collections.sort(entryList, new Comparator<Map.Entry<String, Double>>() { public int compare(Entry<String, Double> entry1, Entry<String, Double> entry2) { double value1 = 0, value2 = 0; try { value1 = entry1.getValue() * 1000; value2 = entry2.getValue() * 1000; } catch (NumberFormatException e) { value1 = 0; value2 = 0; } return (int) (value2 - value1); } }); Iterator<Map.Entry<String, Double>> iter = entryList.iterator(); Map.Entry<String, Double> tmpEntry = null; while (iter.hasNext()) { tmpEntry = iter.next(); sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue()); } } return sortedMap; }}二,测试
public static void main(String[] args) { Map<String,Double> map = new LinkedHashMap<String,Double>(); map.put("no1", 2.25); map.put("no2", 4.4); map.put("no3", 10.0); map.put("no4", 3.51); map.put("no5", 2.05); map.put("no6", 13.1); map.put("no7", 9.77); //对map的value值排序 Map<String,Double> sortMap = MapUtil.sortMapByValue(map); System.out.PRintln(sortMap); }三,打印结果:
{no6=13.1, no3=10.0, no7=9.77, no2=4.4, no4=3.51, no1=2.25, no5=2.05}
新闻热点
疑难解答