java - 排序 LinkedHashMap> 通过计算 ArrayList 中的出现次数问题
问题描述
我有:
ArrayList<String> miss;
LinkedHashMap<String, ArrayList<String>> map;
我如何通过计算“错过”中的出现来对“地图”进行排序?例如:
- 错过 => [3, 7]
- 地图=> {1=[0, 3 , 6], 4=[2, 3 , 4], 6=[0, 3 , 7 ], 11=[1, 3 , 6], 17=[2, 6 , 11]}
我想得到:
地图 => {6=[0, 3, 7], 1=[0, 3, 6], 4=[2, 3, 4], 11=[1, 3, 6], 17=[2, 6 , 11]}
解决方案
以下解决方案基于使用 Stream API
miss
计算每个列表值中元素的频率maps
并将频率收集到某个对象(例如列表)中- 按频率倒序对新对象排序,然后按初始映射的键(注意:键可能需要转换为 int 以提供预期的输出:1、4、11;比较键为 String 返回订单 1, 11, 4 )
Collectors.toMap
使用LinkedHashMap::new
供应商构建生成的地图
List<String> miss = List.of("3", "7");
Map<String, List<String>> maps = Map.of(
"1", List.of("0", "3", "6"),
"4", List.of("2", "3", "4"),
"6", List.of("0", "3", "7"),
"11", List.of("1", "3", "6"),
"17", List.of("2", "6", "11")
);
Map<String, List<String>> sorted = maps.entrySet()
.stream()
.map(e -> Arrays.asList(e,
e.getValue().stream()
.mapToInt(i -> (int) miss.stream().filter(i::equals).count())
.sum()
))
.sorted(Comparator
.<List>comparingInt(ee -> (int) ee.get(1)).reversed()
.thenComparingInt(ee -> Integer.parseInt(((Map.Entry<String, List<String>>) ee.get(0)).getKey()))
)
.map(ee -> (Map.Entry<String, List<String>>) ee.get(0))
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(v1, v2) -> v1,
LinkedHashMap::new
));
System.out.println(sorted);
输出:
{6=[0, 3, 7], 1=[0, 3, 6], 4=[2, 3, 4], 11=[1, 3, 6], 17=[2, 6, 11]}
推荐阅读
- matplotlib - matplotlib:如何自动缩放字体大小以使文本适合某些边界框
- kubernetes - 如何使用 Kubernetes API 获取特定 Kubernetes 集群中所有命名空间的列表?
- wolkenkit - 如何使用/消费来自 wolkenkit-eventstore 的事件流
- php - Laravel 5.8 更新 mysql json 列转换为数组更改数据存储格式
- javascript - 错误类型错误:无法读取未定义的属性“有效”
- linux - 使用 sed 命令将行替换为正则表达式
- java - java - 如何在java swing中创建3个按钮以占据它们添加到的面板的1/3?
- elasticsearch - 在 Kibana 7/6.7.2 中为 DSL 中大小为 1 的最新 _id 设置过滤器
- reactjs - 在使用样式化组件时尝试理解“theme="[object Object]" 的含义
- angular - 子组件输入变量的setter/ngOnChanges方法只调用一次?