Map的序列的排序

来源:互联网 发布:亚投行结局是笑话知乎 编辑:程序博客网 时间:2024/06/08 20:31
package com.jjyy.basic;import java.util.Collections;import java.util.Comparator;import java.util.HashMap;import java.util.LinkedHashMap;import java.util.LinkedList;import java.util.List;import java.util.Map;import java.util.Map.Entry;import java.util.Set;import org.junit.Before;import org.junit.Test;/** * map的排序 * @author jiangyu 2015年9月18日 * */public class SortMapDemo {private Map<String, Integer> map = new HashMap<String, Integer>();/** * Map 排序操作 * @param aMap */private void sortMapByValues(Map<String, Integer> aMap) {Set<Entry<String, Integer>> mapEntities = aMap.entrySet();System.out.println("Values and Keys before sorting ...");System.out.println("V"+" - "+"K");for (Entry<String, Integer> entry : mapEntities) {System.out.println(entry.getValue()+" - "+entry.getKey());}// used linked list to sort ,because insertion of elements in// linked list is faster than an array listList<Entry<String, Integer>> aList  = new LinkedList<Map.Entry<String,Integer>>(mapEntities);//sorting the listCollections.sort(aList, new Comparator<Entry<String, Integer>>() {@Overridepublic int compare(Entry<String, Integer> ele1, Entry<String, Integer> ele2) {return ele1.getValue().compareTo(ele2.getValue());}});//Sorting the list into Linked HashMap to preserve the order of insertion Map<String, Integer> aMap2 = new LinkedHashMap<String, Integer>();for (Entry<String, Integer> entry : aList) {aMap2.put(entry.getKey(), entry.getValue());}//Printing values after sorting of mapSystem.out.println("V"+" - "+"K");for (Entry<String, Integer> entry : aMap2.entrySet()) {System.out.println(entry.getValue() +" - "+entry.getKey());}}@Beforepublic void initValue(){map.put("Six", 6);map.put("One", 1);map.put("Three", 3);map.put("Seven", 7);map.put("Four", 4);map.put("Two", 2);map.put("Five", 5);}@Testpublic void testMapSort(){sortMapByValues(map);}}

结果:

Values and Keys before sorting ...V - K6 - Six7 - Seven5 - Five3 - Three1 - One2 - Two4 - FourV - K1 - One2 - Two3 - Three4 - Four5 - Five6 - Six7 - Seven


0 0
原创粉丝点击