Java7
1 treeMap
/**
* 使用 Map按key进行排序
*
* @param map
* @return
*/
public static Map<String, String> sortMapByKey(Map<String, String> map) {
if (map == null || map.isEmpty()) {
return null;
}
Map<String, String> sortMap = new TreeMap<String, String>(new Comparator<String>() {
@Override
public int compare(String str1, String str2) {
// TODO Auto-generated method stub
return str1.compareTo(str2);
}
});
sortMap.putAll(map);
return sortMap;
}
public static void main(String[] args) {
Map<String, String> map = new TreeMap<String, String>();
map.put("1", "kfc");
map.put("2", "wnba");
map.put("NBA", "nba");
map.put("CBA", "cba");
Map<String, String> resultMap = sortMapByKey(map); //按Key进行排序
for (Map.Entry<String, String> entry : resultMap.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
//2list排序
//list.sort()或者collections.sort
LinkedList<Map.Entry<String,String>> linkedList = new LinkedList<>(map.entrySet());
//jdk1.8
linkedList.sort(new Comparator<Map.Entry<String,String>>() {
@Override
public int compare(Entry<String, String> o1, Entry<String, String> o2) {
return o1.getKey().compareTo(o2.getKey());
}
});
//jdk1.7
Collections.sort(linkedList, new Comparator<Map.Entry<String,String>>(){
@Override
public int compare(Entry<String, String> o1, Entry<String, String> o2) {
// TODO Auto-generated method stub
return o1.getKey().compareTo(o2.getKey());
}
});
// Java8
Map<String, Integer> unsortMap = new HashMap<>();
unsortMap.put("z", 10);
unsortMap.put("b", 5);
unsortMap.put("a", 6);
unsortMap.put("c", 20);
unsortMap.put("d", 1);
unsortMap.put("e", 7);
unsortMap.put("y", 8);
unsortMap.put("n", 99);
unsortMap.put("g", 50);
unsortMap.put("m", 2);
unsortMap.put("f", 9);
System.out.println("Original...");
System.out.println(unsortMap);
// sort by keys, a,b,c..., and return a new LinkedHashMap
// toMap() will returns HashMap by default, we need LinkedHashMap to keep the order.
Map<String, Integer> result = unsortMap.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(oldValue, newValue) -> oldValue, LinkedHashMap::new));
// Not Recommend, but it works.
//Alternative way to sort a Map by keys, and put it into the "result" map
Map<String, Integer> result2 = new LinkedHashMap<>();
unsortMap.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.forEachOrdered(x -> result2.put(x.getKey(), x.getValue()));
System.out.println("Sorted...");
System.out.println(result);
System.out.println(result2);
链接:https://blog.csdn.net/wangmuming/article/details/78448394