java - 基于列表值计数的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(...));
我想按序号排序。住在房子里的人。
我如何使用比较器或比较器来实现这一点?
解决方案
它不应该作为地图键 Home 的属性来完成,因为您可能希望将人员添加/删除到 Home,从而破坏地图。
而是动态排序:
ihm.entrySet().stream()
.sort(Comparator.comparingInt(es -> -es.getValue().size())) // Decreasing; neg. sizes.
.forEach(es -> System.out.printf("...%n", ...));
推荐阅读
- django - 使用 gevent 执行池的 celery 任务的 SynchronousOnlyOperation
- domain-driven-design - 事件溯源 - 如何聚合
- javascript - ONNX.js 中的 Pytorch LSTM - 未捕获(承诺中)错误:节点无法识别的输入“”:LSTM_4
- python - 如何迭代作为函数参数传递的列表?
- python - 如何在 Django Rest Framework 中获取单个项目
- java - 使用 sam stevens totp - 无法正常工作
- angular - 为什么我在编辑 HTML 模板后在 Angular 11 中收到错误 NG6001
- javascript - 使用 AJAX 在 Flask 和 JS 之间发送数据以进行 chrome 扩展
- javascript - 如何从 gist 脚本创建语言选择包装器?
- php - PHP 如何执行命令并获取其输出