Java Hashmap: Swap two values?

南笙酒味 提交于 2019-12-24 06:39:23

问题


Can I swap the keys of two values of a Hashmap, or do I need to do something clever?

Something that would look something like this:

    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;
    }

回答1:


Well, if you're just after a Map where the keys are ordered, use a SortedMap instead.

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

You can rely on the natural ordering of the key (as in, its Comparable interface) or you can do custom ordering by passing a Comparator.

Alternatively you can call setValue() on the Entry.

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;
}

Personally I'd just go with a SortedMap.




回答2:


There's nothing like that in the Map or Entry interfaces but it's quite simple to implement:

    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()));
    }


来源:https://stackoverflow.com/questions/1436290/java-hashmap-swap-two-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!