1. 程式人生 > >Java中map中值按照key鍵和value值分別排序

Java中map中值按照key鍵和value值分別排序

參考:https://www.cnblogs.com/zhujiabin/p/6164826.html

1. 按照key排序,可以藉助有序集合TreeMap實現,如下:

 @Test
  public void sortByMapKey() {
	Map<String,String> map = new HashMap<String,String>();
	 
	
	map.put("KFC","kfc");
	map.put("WNBA", "wnba");
	map.put("NBA", "nba");
	map.put("CBA", "cba");
	 Map<String,String> resultmap =sortByKey(map);
	 //Map<String,String> resultmap = sortByValue(map);
	for (Map.Entry<String, String> entry : resultmap.entrySet()) {
	    System.out.println(entry.getKey() + " " + entry.getValue());
	}
  }


  Map  sortByKey(Map map) {
	 Map<String,String> treeMap = new TreeMap<String,String>(new Comparator<String> 
      () {

		@Override
		public int compare(String str1, String str2) {
			 
			return str1.compareTo(str2);
		}
		 
	 });
	 treeMap.putAll(map);
	 return treeMap;
  }

2. 按照value值排序如下:

原理:將待排序Map中的所有元素置於一個列表中,接著使用Collections的一個靜態方法 sort(List<T> list, Comparator<? super T> c) 來排序列表,同樣是用比較器定義比較規則。排序後的列表中的元素再依次裝入Map,為了肯定的保證Map中元素與排序後的List中的元素的順序一致,使用了LinkedHashMap資料型別。

@Test
  public void sortByMapKey() {
	Map<String,String> map = new HashMap<String,String>();
	 
	
	map.put("KFC","kfc");
	map.put("WNBA", "wnba");
	map.put("NBA", "nba");
	map.put("CBA", "cba");
	// Map<String,String> resultmap =sortByKey(map);
	Map<String,String> resultmap = sortByValue(map);
	for (Map.Entry<String, String> entry : resultmap.entrySet()) {
	    System.out.println(entry.getKey() + " " + entry.getValue());
	}
  }

Map  sortByValue(Map map) {
		List<Map.Entry<String, String>> list = new ArrayList<Map.Entry<String, String>>(map.entrySet());
		Map<String,String> linkedHashMap = new LinkedHashMap<String,String>();
		Collections.sort(list, new Comparator<Map.Entry<String, String>>() {

			 

			@Override
			public int compare(Entry<String, String> entry1, Entry<String, String> entry2) {
				 
				return entry2.getValue().compareTo(entry1.getValue());
			}
			
		});
		Iterator<Map.Entry<String, String>> iterator =  list.iterator();
		Map.Entry<String, String> tempMap = null;
		while(iterator.hasNext()) {
			tempMap = iterator.next();
			linkedHashMap.put(tempMap.getKey(), tempMap.getValue());  
		}
		return linkedHashMap;
	}