如何在Java中按键对Map值排序?

我有一个同时包含键和值的字符串的Map。 java

数据以下: app

“ question1”,“ 1”
“ question9”,“ 1”
“ question2”,“ 4”
“ question5”,“ 2” 函数

我想根据其键对地图进行排序。 所以,最后,我将看到question1, question2, question3 ...等。 this


最终,我试图从该Map中获取两个字符串。 spa

  • 第一个字符串:问题(顺序为1 ..10)
  • 第二个字符串:答案(与问题的顺序相同)

如今,我有如下内容: code

Iterator it = paramMap.entrySet().iterator();
while (it.hasNext()) {
    Map.Entry pairs = (Map.Entry) it.next();
    questionAnswers += pairs.getKey() + ",";
}

这使个人问题成串出现,但顺序不正确。 排序


#1楼

若是您已经有了地图,而且想按键对它进行排序,则只需使用: three

Map<String, String> treeMap = new TreeMap<String, String>(yourMap);

一个完整的工做示例: 字符串

import java.util.HashMap;
import java.util.Set;
import java.util.Map;
import java.util.TreeMap;
import java.util.Iterator;

class SortOnKey {

public static void main(String[] args) {
   HashMap<String,String> hm = new HashMap<String,String>();
   hm.put("3","three");
   hm.put("1","one");
   hm.put("4","four");
   hm.put("2","two");
   printMap(hm);
   Map<String, String> treeMap = new TreeMap<String, String>(hm);
   printMap(treeMap);
}//main

public static void printMap(Map<String,String> map) {
    Set s = map.entrySet();
    Iterator it = s.iterator();
    while ( it.hasNext() ) {
       Map.Entry entry = (Map.Entry) it.next();
       String key = (String) entry.getKey();
       String value = (String) entry.getValue();
       System.out.println(key + " => " + value);
    }//while
    System.out.println("========================");
}//printMap

}//class

#2楼

只需使用TreeMap get

new TreeMap<String, String>(unsortMap);

请注意,TreeMap是根据其“键”的天然顺序排序的


#3楼

此代码能够按升序和降序这两个顺序对键值映射进行排序。

<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;
}

举个例子:

Map<Integer,Double> recommWarrVals = new HashMap<Integer,Double>();
recommWarrVals = sortByValues(recommWarrVals, 1);  // Ascending order
recommWarrVals = sortByValues(recommWarrVals,-1);  // Descending order

#4楼

若是您不能使用TreeMap ,那么在Java 8中,咱们能够使用CollectorstoMap()方法,该方法具备如下参数:

  • keymapper :映射函数以生成密钥
  • valuemapper :映射函数以产生值
  • mergeFunction :一个合并函数,用于解决与同一键关联的值之间的冲突
  • mapSupplier :此函数返回一个新的空Map,将结果插入其中。

Java 8示例

Map<String,String> sample = new HashMap<>();  // push some values to map  
Map<String, String> newMapSortedByKey = sample.entrySet().stream()
                    .sorted(Map.Entry.<String,String>comparingByKey().reversed())
                    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
Map<String, String> newMapSortedByValue = sample.entrySet().stream()
                        .sorted(Map.Entry.<String,String>comparingByValue().reversed())
                        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1,e2) -> e1, LinkedHashMap::new));

咱们能够修改该示例以使用自定义比较器并基于如下项对键进行排序:

Map<String, String> newMapSortedByKey = sample.entrySet().stream()
                .sorted((e1,e2) -> e1.getKey().compareTo(e2.getKey()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1,e2) -> e1, LinkedHashMap::new));

#5楼

在Java 8中,您还能够使用.stream()。sorted():

myMap.keySet().stream().sorted().forEach(key -> {
        String value = myMap.get(key);

        System.out.println("key: " + key);
        System.out.println("value: " + value);
    }
);
相关文章
相关标签/搜索