【问题标题】:Sort value of hashmaphashmap的排序值
【发布时间】:2015-08-09 12:26:54
【问题描述】:

我有下面的hashmap 如下:

  Map<String, Integer> map = new HashMap<String, Integer>();

  map.put("a", 4);
  map.put("b", 9);
  map.put("c", 1);

我想根据它们的值对哈希图进行排序,它应该给出如下输出:

[1, 4, 9]

这可以使用 Comparator 吗?

更新:提供的链接没有提供解决方案,我尝试了解决方案,创建的hashmap无法按键遍历。

【问题讨论】:

  • HashMaps 没有顺序。您需要将这些值存储在其他地方。
  • @Pshemo 是个很大的hashmap,可以存储在别的地方然后按值排序吗?
  • 正如我所说,HashMap 是无序结构,因此您不能对它们强制执行任何顺序。您需要新的结构来存储这些值并稍后对其进行排序。
  • @SMA 我尝试了重复链接中提供的解决方案,但创建的 hashmap 无法按键遍历。

标签: java sorting hashmap


【解决方案1】:

Map 中收集流的Java 8 解决方案:

   Map<String, Integer> map = new HashMap<>();

    map.put("a", 4);
    map.put("b", 9);
    map.put("c", 1);

    Map<String, Integer> orderedByValueMap =
            map.entrySet().stream()
                .sorted(Comparator.comparing(Map.Entry::getValue))
                .collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue,
                        (o1, o2) -> o1, LinkedHashMap::new));

    System.out.println(orderedByValueMap);

输出:{c=1, a=4, b=9}

【讨论】:

    【解决方案2】:
     Map<String, Integer> map = new HashMap<String, Integer>();
          map.put("a", 4);
          map.put("b", 9);
          map.put("c", 1);
          List<Integer> l = new ArrayList<Integer>(map.values());
          l.sort(null);
          System.out.println(l);
    

    此代码根据您的需要提供输出。

    【讨论】:

    • 我现在如何跟踪密钥?
    猜你喜欢
    • 1970-01-01
    • 2020-01-29
    • 1970-01-01
    • 1970-01-01
    • 2021-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多