对 LinkedHashMap<String、ArrayList 进行排序<String>>通过计算 ArrayList 问题中的出现次数<String>



我有:

ArrayList<String> miss;
LinkedHashMap<String, ArrayList<String>> map;

如何对"地图"进行排序?通过计算"miss"one_answers"?"中的出现次数例如:

  1. =比小姐;(3、7)
  2. 地图=比;{1 = [0,3, 6], 4=[2,3, 4], 6=[0,37、], 11=[1,3, 6], [2, 6, 11]}

我想要得到:

地图=比;{6 =[0、3、7],1 = 0、3、6,4 =(2、3、4),11 =(1、3、6),17 = [2,6 11]}

下面的解决方案是基于使用流API

  1. 计算maps的每个列表值中miss元素的频率,并将频率收集到某个对象中(例如列表)
  2. 将新对象按频率反向排序,然后按初始map的键排序(注意:键可能需要转换成int来提供预期的输出:1,4,11;比较键作为String返回顺序1,11,4)
  3. 使用Collectors.toMapLinkedHashMap::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]}

相关内容

最新更新