我可以交换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;
    }
有帮助吗?

解决方案

好吧,如果您只是在订购密钥的地图之后,请使用 SortedMap

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

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

或者,您可以在条目上调用 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

其他提示

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

    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()));
    }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top