首页 > 解决方案 > 基于列表值计数的Java排序映射

问题描述

例如

Map<Home, List<People>> ihm = new TreeMap<Home, List<People>>();

数据如下:

ihm.put(new Home(...), Arrays.asList(new People(...),
new People(...),
new People(...));
ihm.put(new Home(...), Arrays.asList(new People(...),
new People(...));

我想按序号排序。住在房子里的人。

我如何使用比较器或比较器来实现这一点?

标签: javalistsortingtreemap

解决方案


它不应该作为地图键 Home 的属性来完成,因为您可能希望将人员添加/删除到 Home,从而破坏地图。

而是动态排序:

ihm.entrySet().stream()
   .sort(Comparator.comparingInt(es -> -es.getValue().size())) // Decreasing; neg. sizes.
   .forEach(es -> System.out.printf("...%n", ...));

推荐阅读