【问题标题】:HashMaps and operationsHashMap 和操作
【发布时间】:2011-12-11 14:33:33
【问题描述】:

我对 HashMap 有疑问。 我要放入地图:

key - 320, value - 0.1
key - 321, value - 0.7
key - 322, value - 0.5
key - 323, value - 0.6

之后我想像这样按降序对该地图进行排序:

key - 321, value - 0.7
key - 323, value - 0.6
key - 322, value - 0.5
key - 320, value - 0.1

然后我想按升序对地图进行排序,但只有值:

key - 321, value - 0.1
key - 323, value - 0.5
key - 322, value - 0.6
key - 320, value - 0.7

这在哈希图中是可能的吗?我该怎么做?

【问题讨论】:

  • 你真的要在第三步中将映射从键更改为值吗?
  • 我需要更改这个值,因为在下一步我会做一些操作。下一步我必须乘以 321 * 0.1、323 * 0.5 等。除非我可以在不更改映射的情况下做到这一点?

标签: java sorting hashmap


【解决方案1】:

没有。 HashMap 是 Map insteface 的一个实现,它不保留任何键的顺序。它根据它们的哈希码放置密钥。

但是您有更简单的解决方案。您应该改用 TreeMap。这个类接受比较器。将它与您自己的比较器一起使用,您甚至不必对任何东西进行排序。密钥将根据比较器返回。要反转顺序,您可以使用其他 TreeMap 或直接说 new ArrayList(t.keySet()) 然后反转列表的顺序。

【讨论】:

    【解决方案2】:

    不,您不能使用 HashMap 或任何标准 jdk 映射实现按值排序。

    【讨论】:

      【解决方案3】:

      HashMap 不维护顺序,因此无法排序。您应该将键和值放在对象中。

      class Pair {
          int key;
          doulbe value;
      }
      

      将它们放入一个 ArrayList 并使用 Collections.sort() 对其进行排序。

      class Pair {
          int key;
          double value;
      
          public Pair(int key, double value) {
              this.key = key;
              this.value = value;
          }
      }
      
      class Desc implements Comparator<Pair> {
          @Override
          public int compare(Pair o1, Pair o2) {
              return (int) Math.signum(o1.value - o2.value);
          }
      }
      
      class Asc implements Comparator<Pair> {
          @Override
          public int compare(Pair o1, Pair o2) {
              return (int) Math.signum(o2.value - o1.value);
          }
      }
      
      public class Test {
          public static void dump(Collection<Pair> col) {
              for ( Pair p :col ) {
                  System.out.println("key = " + p.key + " value = " + p.value );
              }
          }
          public static void main(String[] args) {
              ArrayList<Pair> p = new ArrayList<Pair>();
              for (int i = 320; i < 325; i++) {
                  p.add(new Pair(i, (double) i / 1000));
              }
              Collections.sort(p, new Asc());
              dump(p);
              System.out.println("------------------------");
              Collections.sort(p, new Desc());
              dump(p);
          }
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-20
        • 2013-02-17
        • 1970-01-01
        • 1970-01-01
        • 2013-04-15
        • 1970-01-01
        相关资源
        最近更新 更多