天天看点

[Java]map按key或value排序

Map排序折方式有很多种,这里只写两种按键排序与按值排序

jdk内置的java.util包下的TreeMap<K,V>既可满足此类需求,向其构造方法 TreeMap(Comparator<? super K> comparator)  传入我们自定义的比较器即可实现按键排序。

<span style="color:#404040;">String url = Config.getXmlConstantUrl() + "/modelData/modelConstant.ac?type=" + Config.STB_PRODUT_NAME;
					String xmlSavePath = UpgradeManager.XML_FILE_PATH;
					//请求平台获取ModelConstant.xml
					boolean isRequestSuc = HttpUrlUtil.sendRequestGetXml(url, xmlSavePath, "ModelConstant.xml");
					if(isRequestSuc){
						//无异常,解析xml
						constant = XmlUtil.parserXmlFile(xmlSavePath + File.separator + "ModelConstant.xml");
					}
					//如网络请求未成功或解析时无xml文件、文件内容格式有误解析异常 将使用默认值
					if(constant == null){
						constant = new TreeMap<String, String>();
						for(int i = 1; i <= 8; i++){
							constant.put("v" + i, "1");
						}
					}
					//map按key排序
					constant = </span><strong><span style="color:#ff0000;">sortMapByKey</span></strong><span style="color:#404040;">(constant);
					StringBuilder builder  = new StringBuilder();
					for(Entry<String, String> mapTemp : constant.entrySet()){
						builder.append(mapTemp.getKey() + ":" + mapTemp.getValue() + ",");
					}</span>
           
/**
	 * 使用 Map按key进行排序
	 * @param map
	 * @return
	 */
	public static Map<String, String> sortMapByKey(Map<String, String> map) {
		if (map == null || map.isEmpty()) {
			return null;
		}

		Map<String, String> sortMap = new TreeMap<String, String>(
				new Comparator<String>() {

					@Override
					public int compare(String str1, String str2) {

						return str1.compareTo(str2);
					}

				});

		sortMap.putAll(map);

		return sortMap;
	}
           

按值排序

将待排序Map中的所有元素置于一个列表中,接着使用Collections的一个静态方法 sort(List<T> list, Comparator<? super T> c) 

来排序列表,同样是用比较器定义比较规则。排序后的列表中的元素再依次装入Map,为了肯定的保证Map中元素与排序后的List中的元素的顺序一致,使用了LinkedHashMap数据类型。

public class Test {
	public static void main(String[] args) {
		Map<String,String> map = new TreeMap<String,String>();
		map.put("AAA","aaa");
		map.put("BBB","bbb");
		map.put("CCC","ccc");

		map = sortMapByValue(map);
	}

	
	private static Map<String, String> sortMapByValue(Map<String, String> map) {
		if (map == null || map.isEmpty()) {
			return null;
		}
		Map<String, String> sortedMap = new LinkedHashMap<String, String>();
		List<Map.Entry<String, String>> entryList = new ArrayList<Map.Entry<String, String>>(
				map.entrySet());
		Collections.sort(entryList,new Comparator<Map.Entry<String,String>>() {

			public int compare(Entry<String, String> o1,
					Entry<String, String> o2) {
				// TODO Auto-generated method stub
				return o1.getValue().compareTo(o2.getValue());
			}

		});

		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;
	}
}