public Map<Integer, List> sort(Map<Integer, List> map){
//Java8中使用Stream对map进行排序
Map<Integer, List> result = map.entrySet().stream()
.sorted(Map.Entry.comparingByKey(
//倒序
Comparator.reverseOrder()
))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(oldValue, newValue) -> oldValue, LinkedHashMap::new));
return result;
}
HashMap
永远是散乱分布的,做不到排序。
可以用TreeMap
,它自带排序功能。
public static void main(String[] args) throws ParseException {
User user = new User("张三");
User user2 = new User("李四");
List<User> list1 = new ArrayList<>();
List<User> list2 = new ArrayList<>();
list1.add(user);
list1.add(user2);
list2.add(user);
list2.add(user2);
Map<Integer, List<User>> map = new HashMap<>();
map.put(9999, list1);
map.put(8888, list2);
map.put(6666, list2);
map.put(7777, list2);
Map<Integer, List<User>> resultMap = new TreeMap<>((str1, str2) -> str2.compareTo(str1));
resultMap.putAll(map);
resultMap.forEach((key,value)-> System.out.println(key+":"+value));
System.out.println(123);
}
转换成TreeMap进行排序,希望可以帮到你’
map定义改为:Map<Integer, List> = new TreeMap<>();
map按key排序直接把map转成 TreeMap 就行了