欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

map排序

程序员文章站 2024-02-17 15:21:40
...

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Test2 {
	public static void main(String[] args) {
		List<Map.Entry<String, String>> mappingList = null;
		Map<String, String> map = new HashMap<String, String>();
		map.put("dddd", "c");
		map.put("aaaa", "b");
		map.put("bbbb", "d");
		map.put("ccccc", "a");
		

		// 通过ArrayList构造函数把map.entrySet()转换成list
		mappingList = new ArrayList<Map.Entry<String, String>>(map.entrySet());
		// 通过比较器实现比较排序
		Collections.sort(mappingList,
				new Comparator<Map.Entry<String, String>>() {
					public int compare(Map.Entry<String, String> mapping1,
							Map.Entry<String, String> mapping2) {
						// return
						// mapping1.getKey().compareTo(mapping2.getKey());
						return mapping1.getValue().compareTo(
								mapping2.getValue());
					}
				});

		for (Map.Entry<String, String> mapping : mappingList) {
			System.out.println(mapping.getKey() + ":" + mapping.getValue());
		}
	}
}