按照Value排序的HashMap

发布时间 2023-08-03 16:50:27作者: Ari的小跟班

按照Value排序的HashMap

直接上代码:

import java.util.*;
public class ValueSortedMap<K, V extends Comparable<V>> extends TreeMap<K, V> {
    private static final long serialVersionUID = 1L;
    private TreeMap<V, Set<K>> valueKeyMap;
    public ValueSortedMap() {
        super();
        valueKeyMap = new TreeMap<>();
    }
    public ValueSortedMap(Comparator<? super V> comparator) {
        super();
        valueKeyMap = new TreeMap<>(comparator);
    }
    @Override
    public V put(K key, V value) {
        if (containsKey(key)) {
            V oldValue = get(key);
            valueKeyMap.get(oldValue).remove(key);
            if (valueKeyMap.get(oldValue).isEmpty()) {
                valueKeyMap.remove(oldValue);
            }
        }
        Set<K> existedSet = valueKeyMap.get(value);
        if (Objects.isNull(existedSet)) {
            HashSet<K> tempSet = new HashSet<>(Collections.singletonList(key));
            valueKeyMap.put(value, tempSet);
        }else{
            existedSet.add(key);
        }

        return super.put(key, value);
    }
    public TreeMap<V, Set<K>> getValueKeyMap() {
        return valueKeyMap;
    }
}

用法:

public static void main(String[] args){
        ValueSortedMap<String, Integer> map = new ValueSortedMap<>();
        map.put("One", 1);
        map.put("Three", 3);
        map.put("Two", 2);
        map.put("Three",0);
        map.put("Three",-2);
        map.put("Four",1);
        System.out.println(map.get("Three"));
        TreeMap<Integer, Set<String>> valueKeyMap = map.getValueKeyMap();
        for (Map.Entry<Integer, Set<String>> entry : valueKeyMap.entrySet()) {
            Integer value = entry.getKey();
            Set<String> keys = entry.getValue();//取的是set;因为同一个value可以有多个key存在。
            for (String key : keys) {
                System.out.println("Key: " + key + ", Value: " + value);
            }
        }
    }

​ 遍历的时候通过 NavigableMap<Integer, Set<String>> valueKeyMap = map.getValueKeyMap();中的entrySet()进行遍历。其实就是在TreeMap的基础上再加一个用value作为键,Set作为值的TreeMap内部对象,该对象的值Set是value=键的key的集合。因为TreeMap默认是按照键排序的。