`

对Map进行排序

    博客分类:
  • java
阅读更多

HashMap是无序的

TreeMap 是按key升序的 不能按value排序

LinkedHashMap 放进去的是什么顺序就是什么顺序

 

代码如下:

public class Test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		Map<String,Integer> map = new HashMap<String, Integer>();
		map.put("zhangsan", 18);
		map.put("lisi", 17);
		map.put("wangwu", 30);
		map.put("maliu", 25);
		map.put("subi", 26);
		
		
		Set<Entry<String,Integer>> set = map.entrySet();
		List<Entry<String,Integer>> list = new ArrayList(set);
		Collections.sort(list, new Comparator<Entry<String,Integer>>() {
			@Override
			public int compare(Entry<String, Integer> o1,
					Entry<String, Integer> o2) {
//				if (o1.getValue() < o2.getValue()) {
//					return -1;
//				} else if (o1.getValue() > o2.getValue()) {
//					return 1;
//				} else {
//					return 0;
//				}
				return o1.getValue().compareTo(o2.getValue());
			}
		});
		
		map.clear();
		map = new LinkedHashMap<String, Integer>();
		for(Entry<String,Integer> entry: list){
			map.put(entry.getKey(), entry.getValue());
		}
		
		for(Entry<String,Integer> entry: map.entrySet()){
			System.err.println(entry.getKey() + "=" + entry.getValue());
		}
	}

}
 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics