简体   繁体   English

Java:如何使用通用键和值对HashMap的值进行排序?

[英]Java : How to sort values of a HashMap with generic Key and Value?

I have a TreeMap that i need to Sort-By-Values. 我有一个TreeMap,我需要按值对它们进行排序。 I am able sort the Map if the values are Integer type. 如果值是Integer类型,则可以对Map进行排序。

public class MapSorting {

    public static Map<String, Integer> sortByValues(Map<String, Integer> tempMap) {

        ValueComparator bvc = new ValueComparator(tempMap);
        Map<String, Integer> sortedMap = new TreeMap<String, Integer>(bvc);
        sortedMap.putAll(tempMap);
        return sortedMap;

    }
}


class ValueComparator implements Comparator<String> {

        Map<String, Integer> base;

        public ValueComparator(Map<String, Integer> base) {
            this.base = base;
        }

        public int compare(String a, String b) {
            if (base.get(a) >= base.get(b)) {
                return -1;
            } else {
                return 1;
            }
        }
    }

But how do i make the method generic?? 但是我如何使该方法通用? I want to be able to send Map with Key and Value of any type to this method. 我希望能够将具有任何类型的键和值的Map发送到此方法。

I want to return a TreeMap that is sorted based on values. 我想返回一个基于值排序的TreeMap。

Can anyone please help? 谁能帮忙吗?

Note : A TreeMap is intended to be sorted by key, not by value. 注意TreeMap旨在按键而不是按值排序。 That makes me think that you should use another data structure to store your result : eg List<Entry<K, V>> . 那让我认为您应该使用另一个数据结构来存储结果:例如List<Entry<K, V>>

Note : I highly discourage to use this piece of code because I think it is an anti-pattern. 注意 :我强烈不鼓励使用这段代码,因为我认为这是一种反模式。 I did it only to show how it would be possible. 我这样做只是为了表明这将是可能的。

That said, I made it like this (need at least Java 8 or adapt the code) : 就是说,我做到了这一点(至少需要Java 8或修改代码):

public static <K, V extends Comparable> Map<K, V> sortByValues(Map<K, V> tempMap) {
  TreeMap<K, V> map = new TreeMap<>(buildComparator(tempMap));
  map.putAll(tempMap);
  return map;
}

public static <K, V extends Comparable> Comparator<? super K> buildComparator(final Map<K, V> tempMap) {
  return (o1, o2) -> tempMap.get(o1).compareTo(tempMap.get(o2));
}

Test : 测试:

Map<Integer, String> map = new HashMap<>();
map.put(1, "B");
map.put(2, "C");
map.put(3, "A");

for(Map.Entry<Integer, String> entry : sortByValues(map).entrySet()) {
  System.out.println(entry.getKey()+" : "+ entry.getValue());
}

Output : 输出:

3 : A
1 : B
2 : C

Note : I dit not handle null cases because it is not important for this explanation. 注意 :我不处理空值情况,因为这对于此解释并不重要。

You can create a comparator that compares values that are Comparable : 您可以创建一个比较器来比较Comparable的值:

class ValueComparator<Comparable> implements Comparator<Comparable> {

    Map<String, Comparable> base;

    public ValueComparator(Map<String, Comparable> base) {
        this.base = base;
    }

    public int compare(Comparable a, Comparable b) {
        return a.compareTo(b);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM