java - 按 HashMap 的值(按映射的值比较)对 HashMap 的数组列表进行排序

标签 java arraylist java-8 hashmap comparator

<分区>

我的列表看起来像这样

List<Map<CustomClass,Integer>> sampleList = new ArrayList<>();

这里每个自定义类都与一个值相关联,其中该类被视为键,与之关联的值是 map 的值。我可以有多个 1 键具有相同的值。

例如:

List<Map<CustomClass,Integer>> sampleList = new ArrayList<>();


CustomClass a1 = new CustomClass();
CustomClass a2 = new CustomClass();

CustomClass b1 = new CustomClass();
CustomClass b2 = new CustomClass();

Map<CustomClass, Integer> map1 = new HashMap();
map1.put(a1,3);
map1.put(a2,3);

Map<CustomClass, Integer> map2 = new HashMap();
map2.put(b1,2);
map2.put(b2,2);

sampleList.add(map1);
sampleList.add(map2);

现在我希望最终排序的列表具有 {b1,b2,a1,a2},即根据整数值排序。

最佳答案

您可以使用流来展平 map 并按值排序:

List<CustomClass> result = sampleList.stream()
        .map(Map::entrySet)
        .flatMap(Set::stream)
        .sorted(Entry.comparingByValue())
        .map(Entry::getKey)
        .collect(Collectors.toList());

关于java - 按 HashMap 的值(按映射的值比较)对 HashMap 的数组列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67965368/

相关文章:

java - 将包含 "ñ"等字符的字符串写入 txt 文件

java - 如何对我的 ArrayList 实现插入排序?

java - 二叉搜索树路径列表

java - 获取文件的最后修改日期/时间作为本地日期/时间字符串

java - 包含用于参数传递的方法/函数的数组

java - 如何将二维字符数组写入文件

java - Jenkins Sonar 扫描仪与 Maven Sonar :sonar goal

java - Firestore 字段的数组值求和

java - 如何在 shell 脚本中运行 Picard(生物信息学)工具时消除 Java 异常错误?

java - Android 每 5 秒循环一次服务并在启动时启动