How to sort Map values by key in Java?

后端 未结 15 2207
野性不改
野性不改 2020-11-22 08:26

I have a Map that has strings for both keys and values.

Data is like following:

\"question1\", \"1\"
\"question9\", \"1\"
\"que

相关标签:
15条回答
  • 2020-11-22 08:51

    In Java 8

    To sort a Map<K, V> by key, putting keys into a List<K>:

    List<K> result = map.keySet().stream().sorted().collect(Collectors.toList());
    

    To sort a Map<K, V> by key, putting entries into a List<Map.Entry<K, V>>:

    List<Map.Entry<K, V>> result =
        map.entrySet()
           .stream()
           .sorted(Map.Entry.comparingByKey())
           .collect(Collectors.toList());
    

    Last but not least: to sort strings in a locale-sensitive manner - use a Collator (comparator) class:

    Collator collator = Collator.getInstance(Locale.US);
    collator.setStrength(Collator.PRIMARY); // case insensitive collator
    
    List<Map.Entry<String, String>> result =
        map.entrySet()
           .stream()
           .sorted(Map.Entry.comparingByKey(collator))
           .collect(Collectors.toList());
    
    0 讨论(0)
  • 2020-11-22 08:54

    Use a TreeMap!

    0 讨论(0)
  • 2020-11-22 09:04

    We can also sort the key by using Arrays.sort method.

    Map<String, String> map = new HashMap<String, String>();
    Object[] objArr = new Object[map.size()];
    for (int i = 0; i < map.size(); i++) {
    objArr[i] = map.get(i);
    }
    Arrays.sort(objArr);
    for (Object str : objArr) {
    System.out.println(str);
    }
    
    0 讨论(0)
  • 2020-11-22 09:04

    A good solution is provided here. We have a HashMap that stores values in unspecified order. We define an auxiliary TreeMap and we copy all data from HashMap into TreeMap using the putAll method. The resulting entries in the TreeMap are in the key-order.

    0 讨论(0)
  • 2020-11-22 09:06

    This code can sort a key-value map in both orders i.e. ascending and descending.

    <K, V extends Comparable<V>> Map<K, V> sortByValues
         (final Map<K, V> map, int ascending)
    {
         Comparator<K> valueComparator =  new Comparator<K>() {         
            private int ascending;
            public int compare(K k1, K k2) {
                int compare = map.get(k2).compareTo(map.get(k1));
                if (compare == 0) return 1;
                else return ascending*compare;
            }
            public Comparator<K> setParam(int ascending)
            {
                this.ascending = ascending;
                return this;
            }
        }.setParam(ascending);
    
        Map<K, V> sortedByValues = new TreeMap<K, V>(valueComparator);
        sortedByValues.putAll(map);
        return sortedByValues;
    }
    

    As an example:

    Map<Integer,Double> recommWarrVals = new HashMap<Integer,Double>();
    recommWarrVals = sortByValues(recommWarrVals, 1);  // Ascending order
    recommWarrVals = sortByValues(recommWarrVals,-1);  // Descending order
    
    0 讨论(0)
  • 2020-11-22 09:09

    Assuming TreeMap is not good for you (and assuming you can't use generics):

    List sortedKeys=new ArrayList(yourMap.keySet());
    Collections.sort(sortedKeys);
    // Do what you need with sortedKeys.
    
    0 讨论(0)
提交回复
热议问题