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

Java 如何按值对HashMap排序,但保持重复的顺序?,java,dictionary,hashmap,linkedhashmap,Java,Dictionary,Hashmap,Linkedhashmap,我正在尝试将表probability映射排序为一个名为sorted的新映射。在表格概率中的值如下: 钥匙 价值 M 0.1 U 0.3 L 0.3 T 0.2 我 0.1 你可能想这样做。这是常见的操作。如果要返回树映射,可以在下面指定它。通常情况下,一个分配给接口类型。对于TreeMap,它将是NavigableMap Map<Character, Double> sorted = tableProbability.entrySet().stream()

我正在尝试将
表probability
映射排序为一个名为
sorted
的新映射。在
表格概率中
的值如下:

钥匙 价值 M 0.1 U 0.3 L 0.3 T 0.2 我 0.1
你可能想这样做。这是常见的操作。如果要返回
树映射
,可以在下面指定它。通常情况下,一个分配给接口类型。对于
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
                        ));
Map排序=
tableProbability.entrySet().stream()
.排序(Map.Entry.comparingByValue(
Comparator.reverseOrder())
.collect(Collectors.toMap)(条目::getKey,
条目::getValue,
(a,b)->a,//合并,此处不使用,但
//语法要求的
LinkedHashMap::新建//要返回的映射类型
));

您的代码运行良好,但您可以将其简化如下:

  • 源地图:

    LinkedHashMap表=
    新LinkedHashMap(){{
    put('M',0.1);
    put('U',0.3);
    put('L',0.3);
    put('T',0.2);
    put('I',0.1);
    }};
    
    System.out.println(表概率);
    //{M=0.1,U=0.3,L=0.3,T=0.2,I=0.1}
    
  • 此代码工作正常:

    LinkedHashMap排序=新建LinkedHashMap();
    tableProbability.entrySet()
    .stream()
    .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
    .forEachOrdered(x->sorted.put(x.getKey(),x.getValue());
    
    System.out.println(已排序);
    //{U=0.3,L=0.3,T=0.2,M=0.1,I=0.1}
    
  • 简化版:

    LinkedHashMap sorted2=tableProbability
    .entrySet().stream()
    .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
    .collect(LinkedHashMap::新建,
    (col,e)->col.put(e.getKey(),e.getValue()),
    HashMap::putAll);
    
    System.out.println(已分拣的d2);
    //{U=0.3,L=0.3,T=0.2,M=0.1,I=0.1}
    


  • 另请参见:

    使用复合比较仪:

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