繁体   English   中英

如何按值对 HashMap 进行排序但保持重复的顺序?

[英]How to sort a HashMap by value but keep the order of duplicates?

我正在尝试将tableProbability map 排序为一个名为sorted的新表。 tableProbability中,值如下:

钥匙 价值
0.1
ü 0.3
大号 0.3
0.2
0.1

我有以下代码对Map进行排序:

LinkedHashMap<Character, Double> sorted = new LinkedHashMap<>();
tableProbability.entrySet()
        .stream()
        .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
        .forEachOrdered(x -> sorted.put(x.getKey(), x.getValue()));

但我最终得到的是以下Map

钥匙 价值
大号 0.3
ü 0.3
0.2
0.1
0.1

我应该得到的是:

钥匙 价值
ü 0.3
大号 0.3
0.2
0.1
0.1

有没有办法保留重复的订单,或者至少在找到重复的订单时将其放在具有相同价值的订单之上?

您的代码工作正常,但您可以将其简化如下:

  1. 来源 map:

     LinkedHashMap<Character, Double> tableProbability = new LinkedHashMap<>() {{ put('M', 0.1); put('U', 0.3); put('L', 0.3); put('T', 0.2); put('I', 0.1); }};
     System.out.println(tableProbability); // {M=0.1, U=0.3, L=0.3, T=0.2, I=0.1}
  2. 此代码工作正常:

     LinkedHashMap<Character, Double> sorted = new LinkedHashMap<>(); tableProbability.entrySet().stream().sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())).forEachOrdered(x -> sorted.put(x.getKey(), x.getValue()));
     System.out.println(sorted); // {U=0.3, L=0.3, T=0.2, M=0.1, I=0.1}
  3. 简化版:

     LinkedHashMap<Character, Double> sorted2 = tableProbability.entrySet().stream().sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())).collect(LinkedHashMap::new, (col, e) -> col.put(e.getKey(), e.getValue()), HashMap::putAll);
     System.out.println(sorted2); // {U=0.3, L=0.3, T=0.2, M=0.1, I=0.1}

另请参阅:使用流按 List<String> 排序 Map<String, Integer>

你可能想这样做。 是普通操作。 如果要返回TreeMap ,可以在下面指定。 并且通常一个分配给接口类型。 对于TreeMap ,它将是NavigableMap

Map<Character, Double> sorted =
        tableProbability.entrySet().stream()
                .sorted(Map.Entry.comparingByValue(
                        Comparator.reverseOrder()))
                .collect(Collectors.toMap(Entry::getKey,
                        Entry::getValue,
                        (a,b)->a, // merge, not used here but
                                  // syntactically required
                        LinkedHashMap::new // type of map to return
                        ));

使用复合比较器:

.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())
    .andThen(Map.Entry.comparingByKey())
)
    

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM