我有一个地图,有字符串的键和值。

数据如下所示:

“问题1”,“1” “question9”、“1” “问题2”、“4” “问题5”、“2”

我想根据键对映射进行排序。所以,最后,我将得到问题1,问题2,问题3,等等。

最终,我试图从这个Map中得到两个字符串:

第一串:问题(按顺序1 ..10) 第二串:答案(与问题顺序相同)

现在我有以下内容:

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

这让我得到了一个字符串中的问题,但它们不是按顺序排列的。


当前回答

这段代码可以对键值映射进行两种排序,即升序和降序。

<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

其他回答

这段代码可以对键值映射进行两种排序,即升序和降序。

<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
List<String> list = new ArrayList<String>();
Map<String, String> map = new HashMap<String, String>();
for (String str : map.keySet()) {
  list.add(str);
}

Collections.sort(list);

for (String str : list) {
  System.out.println(str);
}

如果你不能使用TreeMap,在Java 8中,我们可以使用collector中的toMap()方法,该方法接受以下参数:

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

假设TreeMap不适合你(假设你不能使用泛型):

List sortedKeys=new ArrayList(yourMap.keySet());
Collections.sort(sortedKeys);
// Do what you need with sortedKeys.

使用树地图!