首页 > 解决方案 > 如何将我的 SortedSet 转换为带有 while 循环的 Map?

问题描述

在以下方法中,我按值对 TreeMap 进行排序......现在我想将 SortedSet 中的条目添加到地图中。

static <K, V extends Comparable<? super V>>
SortedSet<Map.Entry<K, V>> entriesSortedByValues(Map<K, V> map) {
    SortedSet<Map.Entry<K, V>> sortedEntries = new TreeSet<Map.Entry<K, V>>(
            new Comparator<Map.Entry<K, V>>() {
                @Override
                public int compare(Map.Entry<K, V> e1, Map.Entry<K, V> e2) {
                    int res = e1.getValue().compareTo(e2.getValue());
                    return res != 0 ? res : 1;
                }
            }
    );
    sortedEntries.addAll(map.entrySet());
    return sortedEntries;
}

标签: genericswhile-looptreemapsortedset

解决方案


这个方法会做

static <K, V> Map<K, V> toMap(Collection<Map.Entry<K, V>> coll) {
  Map<K, V> map = new LinkedHashMap<>();
  for (Map.Entry<K, V> e : coll) {
    map.put(e.getKey(), e.getValue());
  }
  return map;
}

map您可以在此处为变量使用任何映射。但是由于您之前对条目进行了排序,您可能希望保留顺序。那么LinkedHashMap将是一个不错的选择。也许您想在界面中表达这一点并改为编写:

static <K, V> LinkedHashMap<K, V> toMap(Collection<Map.Entry<K, V>> coll) {

请注意,您Comparator的无效。这必须始终正确,但不是:

comparator.compare(e, e) == 0

推荐阅读