How print out the contents of a HashMap in ascending order based on its values?

前端 未结 13 1502
春和景丽
春和景丽 2020-12-24 11:58

I have this HashMap that I need to print out in ascending order according to the values contained in it (not the keys

相关标签:
13条回答
  • 2020-12-24 12:30

    The simplest solution would be to use a sorted map like TreeMap instead of HashMap. If you do not have control over the map construction, then the minimal solution would be to construct a sorted set of keys. You don't really need a new map.

    Set<String> sortedKeys = new TreeSet<String>();
    sortedKeys.addAll(codes.keySet());
    
    for(String key: sortedKeys){
        println(key  + ":" + codes.get(key));
    }
    
    0 讨论(0)
  • 2020-12-24 12:32

    Try:

    try
    {
        int cnt= m.getSmartPhoneCount("HTC",true);      
        System.out.println("total count of HTC="+cnt);
    }  
    catch (NoSuchBrandSmartPhoneAvailableException e)
    {
        // TODO Auto-generated catch 
        e.printStackTrace();
    }
    
    0 讨论(0)
  • 2020-12-24 12:35

    you just need to use:

     Map<>.toString().replace("]","\n");
    

    and replaces the ending square bracket of each key=value set with a new line.

    0 讨论(0)
  • 2020-12-24 12:36

    You'll need to make a list of the keys, sort them according to the corresponding values, then iterate over the sorted keys.

    Map<String, String> map = getMyMap();
    List<String> keys = new ArrayList<String>(map.keySet());
    Collections.sort(keys, someComparator);
    for (String key: keys) {
        System.out.println(key + ": " + map.get(key));
    }
    

    As for what to use for someComparator, here are some handy, generic Comparator-creating routines I often find useful. The first one sorts by the values according to their natural ordering, and the second allows you to specify any arbitrary Comparator to sort the values:

    public static <K, V extends Comparable<? super V>>
            Comparator<K> mapValueComparator(final Map<K, V> map) {
        return new Comparator<K>() {
            public int compare(K key1, K key2) {
                return map.get(key1).compareTo(map.get(key2));
            }
        };
    }
    
    public static <K, V>
            Comparator<K> mapValueComparator(final Map<K, V> map,
                                             final Comparator<V> comparator) {
        return new Comparator<K>() {
            public int compare(K key1, K key2) {
                return comparator.compare(map.get(key1), map.get(key2));
            }
        };
    }
    
    0 讨论(0)
  • 2020-12-24 12:40

    You aren't going to be able to do this from the HashMap class alone.

    I would take the Map<String, String> codes, construct a reverse map of TreeMap<String, String> reversedMap where you map the values of the codes Map to the keys (this would require your original Map to have a one-to-one mapping from key-to-value). Since the TreeMap provides Iterators which returns entries in ascending key order, this will give you the value/key combination of the first map in the order (sorted by values) you desire.

    Map<String, String> reversedMap = new TreeMap<String, String>(codes);
    
    //then you just access the reversedMap however you like...
    for (Map.Entry entry : reversedMap.entrySet()) {
        System.out.println(entry.getKey() + ", " + entry.getValue());
    }
    

    There are several collections libraries (commons-collections, Google Collections, etc) which have similar bidirectional Map implementations.

    0 讨论(0)
  • 2020-12-24 12:40

    You can use a list of the entry set rather than the key set and it is a more natural choice given you are sorting based on the value. This avoids a lot of unneeded lookups in the sorting and printing of the entries.

    Map<String, String> map = ...
    List<Map.Entry<String, String>> listOfEntries = new ArrayList<Map.Entry<String, String>>(map.entrySet());
    Collections.sort(listOfEntries, new SortByValueComparator());
    for(Map.Entry<String, String> entry: listOfEntries)
       System.out.println(entry);
    
    static class SortByValueComparator implements Comparator<Map.Entry<String, String>> {
       public int compareTo(Map.Entry<String, String> e1, Map.Entry<String, String> e2) {
           return e1.getValue().compateTo(e2.getValue());
       }
    }
    
    0 讨论(0)
提交回复
热议问题