Map按Key和Value排序

Java 2018/03/15 00:03

1.按Key升序排序,使用TreeMap

Map<Integer, Integer> map = new TreeMap<Integer, Integer>();

2.按Key降序排序,修改TreeMap的排序方式

Map< Integer,Integer> map=new HashMap<>();
Comparator<Map.Entry<Integer, Integer>> valueComparator=new Comparator<Map.Entry<Integer,Integer>>() {
  @Override
  public int compare(Entry<Integer, Integer> arg0, Entry<Integer, Integer> arg1) {
    return arg1.compareTo(arg0);
  }
};
List<Map.Entry<Integer, Integer>> list=new ArrayList<Map.Entry<Integer,Integer>>(map.entrySet());
Collections.sort(list,valueComparator);
for(Map.Entry<Integer, Integer> entry:list) {
  System.out.println(entry.getKey()+":"+entry.getValue());
}

3.按Value升序排序,修改TreeMap的排序方式

Map< Integer,Integer> map=new HashMap<>();
Comparator<Map.Entry<Integer, Integer>> valueComparator=new Comparator<Map.Entry<Integer,Integer>>() {
  @Override
  public int compare(Entry<Integer, Integer> arg0, Entry<Integer, Integer> arg1) {
    return arg0.getValue()-arg1.getValue();
  }
};
List<Map.Entry<Integer, Integer>> list=new ArrayList<Map.Entry<Integer,Integer>>(map.entrySet());
Collections.sort(list,valueComparator);
for(Map.Entry<Integer, Integer> entry:list) {
  System.out.println(entry.getKey()+":"+entry.getValue());
}

4.按Value降序排序,同理(略)

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!

Powered by codetiler.com