java - 根据键和值对映射进行排序

标签 java sorting map

我想根据键和值对 Map 进行排序。首先是关键,然后是值(value)。 例如,这应该是结果;

1,2 1,3 2,1 2,2

有人对如何有效地实现这一点有什么建议吗?我一直看到人们使用 TreeMap 对键进行排序,但我也需要值。

或者欢迎使用任何其他方法对键和值对进行排序。

最佳答案

import java.util.SortedSet;
import java.util.TreeSet;

public class SortMapOnKeyAndValue {

    public static void main(String[] args) {
        SortedSet<KeyValuePair> sortedSet = new TreeSet<KeyValuePair>();
        sortedSet.add(new KeyValuePair(1, 2));
        sortedSet.add(new KeyValuePair(2, 2));
        sortedSet.add(new KeyValuePair(1, 3));
        sortedSet.add(new KeyValuePair(2, 1));

        for (KeyValuePair keyValuePair : sortedSet) {
            System.out.println(keyValuePair.key+","+keyValuePair.value);
        }
    }
}
class KeyValuePair implements Comparable<KeyValuePair>{
    int key, value;

    public KeyValuePair(int key, int value) {
        super();
        this.key = key;
        this.value = value;
    }

    public int compareTo(KeyValuePair o) {
        return key==o.key?value-o.value:key-o.key;
    }
}

关于java - 根据键和值对映射进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6546782/

相关文章:

java - 将数组传递给构造函数

android - Osmdroid map 旋转

java - 无法使用 SAXFilter 删除 SOAP 响应的命名空间

java - HttpUrlConnection getResponseCode 抛出 java.net.SocketException : Unexpected end of file from server

c++ - 如何使用 Functor 对集合进行排序

c++ - 使用 std::sort 对二维数组进行排序(基于列)

java - Collections.sort 对 java 对象列表进行排序

api - 在 Google Maps API v3 中打开/关闭标记

java - 如何用整数创建一个简单的 HashMap?

java - Android-值未插入数据库