【问题标题】:Java Hashmap: Swap two values?Java Hashmap:交换两个值?
【发布时间】:2009-09-17 01:21:39
【问题描述】:

我可以交换 Hashmap 的两个值的键,还是我需要做一些聪明的事情?

看起来像这样的东西:

    Map.Entry<Integer, String> prev = null;
    for (Map.Entry<Integer, String> entry: collection.entrySet()) {
        if (prev != null) {
            if (entry.isBefore(prev)) {
                entry.swapWith(prev)
            }
        }
        prev = entry;
    }

【问题讨论】:

  • 您是否尝试使用键对一堆项目进行排序?只需使用 TreeMap 并提供 Comparator 或覆盖 equals 和 compareTo。
  • 这可能需要更多解释。什么是整数键?他们是否执行某种命令?如果是这样,并且如果您基于 String 值进行排序,为什么不直接使用 List 呢?还是这把钥匙有其他含义?

标签: java hashmap swap


【解决方案1】:

好吧,如果您只是在排序键的 Map 之后,请改用 SortedMap

SortedMap<Integer, String> map = new TreeMap<Integer, String>();

您可以依赖键的自然排序(如其Comparable 接口),也可以通过传递Comparator 进行自定义排序。

您也可以在Entry 上致电setValue()

Map.Entry<Integer, String> prev = null;
for (Map.Entry<Integer, String> entry: collection.entrySet()) {
  if (prev != null) {
    if (entry.isBefore(prev)) {
      String current = entry.getValue();
      entry.setValue(prev.getValue();
      prev.setValue(current);
    }
  }
  prev = entry;
}

我个人会选择SortedMap

【讨论】:

【解决方案2】:

MapEntry 接口中没有类似的东西,但实现起来非常简单:

    Map.Entry<Integer, String> prev = null;
    for (Map.Entry<Integer, String> entry: collection.entrySet()) {
            if (prev != null) {
                    if (entry.isBefore(prev)) {
                            swapValues(e, prev);
                    }
            }
            prev = entry;
    }

    private static <V> void swapValues(Map.Entry<?, V> first, Map.Entry<?, V> second)
    {
            first.setValue(second.setValue(first.getValue()));
    }

【讨论】:

    猜你喜欢
    • 2020-05-21
    • 1970-01-01
    • 2014-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-06
    • 1970-01-01
    • 2012-04-12
    相关资源
    最近更新 更多