在键和值上对地图进行排序 [英] Sort a map on key and value

查看:74
本文介绍了在键和值上对地图进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对键和值上的Map进行排序.首先是关键,然后是价值. 例如,这应该是结果;

I want to sort a Map on key and value. First on key then on value. For example, this should be the result;

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

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

任何人都对如何有效实现此建议?我一直在看到人们使用TreeMap对键进行排序,但是我也需要值.

Anyone has a suggestion on how to achieve this effectively? I've been seeing people using a TreeMap to sort keys, however i also need values.

或者欢迎使用其他对键和值进行排序的方法.

Or ofcouse any other method of sorting pairs on key and value is welcome.

推荐答案

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

这篇关于在键和值上对地图进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆