> 通过计算 ArrayList 中的出现次数问题,java,sorting,arraylist,linkedhashmap"/>

首页 > 解决方案 > 排序 LinkedHashMap> 通过计算 ArrayList 中的出现次数问题

问题描述

我有:

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

我如何通过计算“错过”中的出现来对“地图”进行排序?例如:

  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]}

标签: javasortingarraylistlinkedhashmap

解决方案


以下解决方案基于使用 Stream API

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

推荐阅读