Sorting LinkedHashMap<String, ArrayList<String>> by counting the occurrences in ArrayList<String> 问题

Sorting LinkedHashMap<String, ArrayList<String>> by counting the occurrences in ArrayList<String> problem

我有:

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

如何通过计算“miss”出现的次数来对“maps”进行排序?例如:

  1. 小姐 => [3, 7]
  2. 地图 => {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

  1. 计算 miss 的元素在 maps 的每个列表值中的频率,并将频率收集到某个对象(例如列表)中
  2. 按相反顺序按频率对新对象排序,然后按初始映射的键排序(注意:可能需要将键转换为 int 以提供预期输出:1、4 , 11; 比较键作为字符串 returns 顺序 1, 11, 4)
  3. 使用 Collectors.toMapLinkedHashMap::new 供应商
  4. 构建生成的地图
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]}