可以通过将Map转换为List,然后使用Collections.sort方法进行排序,最后将排序后的List转换为Map。
示例代码:
import java.util.*;
public class SortMapByValueLength {
public static void main(String[] args) {
Map> map = new HashMap<>();
map.put(1, new HashMap<>());
map.get(1).put(1, 111);
map.put(2, new HashMap<>());
map.get(2).put(1, 111);
map.get(2).put(2, 222);
map.put(3, new HashMap<>());
map.get(3).put(1, 111);
System.out.println("排序前:" + map);
List>> list = new ArrayList<>(map.entrySet());
Collections.sort(list, (o1, o2) ->
Integer.compare(
o1.getValue().size(),
o2.getValue().size())
);
Map> sortedMap = new LinkedHashMap<>();
for (Map.Entry> entry : list) {
sortedMap.put(entry.getKey(), entry.getValue());
}
System.out.println("排序后:" + sortedMap);
}
}
输出结果:
排序前:{1={}, 2={1=111, 2=222}, 3={1=111}}
排序后:{1={}, 3={1=111}, 2={1=111, 2=222}}