import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import org.junit.Test;
public class MapSortTest {
static Map<String, Integer> MAP = new HashMap<String, Integer>();
static {
MAP.put("ab", 27);
MAP.put("aa", 25);
MAP.put("c", 30);
MAP.put("e", 21);
MAP.put("d", 22);
}
@Test
public void sortByKey() {
TreeMap<String, Integer> treeMap = new TreeMap<String, Integer>(MAP);
for (String key : treeMap.keySet()) {
System.out.printf("key:%s, value:%d\n", key, MAP.get(key));
}
}
@Test
public void sortByValue() {
ArrayList<Entry<String, Integer>> entries = new ArrayList<Entry<String, Integer>>(MAP.entrySet());
Collections.sort(entries, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return (o2.getValue() - o1.getValue()); // 降序
}
});
for (Entry<String, Integer> entry : entries) {
System.out.printf("key:%s, value:%d\n", entry.getKey(), entry.getValue());
}
}
}
--end
本文介绍了一种使用Java实现的Map排序方式,包括按Key升序排序和按Value降序排序的方法。通过TreeMap和自定义Comparator实现了不同场景下的排序需求。

被折叠的 条评论
为什么被折叠?



