欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java中使用map排序的实例讲解

程序员文章站 2022-06-22 14:06:59
对列表进行排序也是我们经常遇到的问题,这里缩小一下范围,使用map来对列表排序。相信大家都有过treemap排序的经历,不过map.entry能按值进行排序,在用法上略胜一筹。下面我们会对这两种map...

对列表进行排序也是我们经常遇到的问题,这里缩小一下范围,使用map来对列表排序。相信大家都有过treemap排序的经历,不过map.entry能按值进行排序,在用法上略胜一筹。下面我们会对这两种map排序的方法分别进行介绍,着重讲解map.entry排序的方法。

1.map.entry方法

把map.entry放进list,再用comparator对list进行排序

list list = new arraylist(map.entryset());
collections.sort(list, (entry e1, entry e2)-> {
  return e1.getkey().compareto(e2.getkey());
});

实例代码:

public class sortkeysmaptest {
  public static void main(string[] args) {
    map<string, string> map = new hashmap<>();
    map.put("2010", "jay");
    map.put("1999", "whx");
    map.put("3010", "huaxiao");
    list<map.entry<string,string>> list = new arraylist<>(map.entryset());
    collections.sort(list, (map.entry e1, map.entry e2)-> {
        return e1.getkey().tostring().compareto(e2.getkey().tostring());
    });

    for (map.entry entry : list) {
      system.out.println("key:" + entry.getkey() + ",value:" + entry.getvalue());
    }
 
  }
}

2.treemap

treemap默认是升序的,如果我们需要改变排序方式,则需要使用比较器:comparator。comparator可以对集合对象或者数组进行排序的比较器接口,实现该接口的public compare(t o1,to2)方法即可实现排序,如下:

import java.util.comparator;
import java.util.iterator;
import java.util.map;
import java.util.set;
import java.util.treemap;
public class treemaptest {
public static void main(string[] args) {
map<string, string> map = new treemap<string, string>(
new comparator<string>() {
public int compare(string obj1, string obj2) {
// 降序排序
return obj2.compareto(obj1);
}
});
map.put("b", "ccccc");
map.put("d", "aaaaa");
map.put("c", "bbbbb");
map.put("a", "ddddd");
set<string> keyset = map.keyset();
iterator<string> iter = keyset.iterator();
while (iter.hasnext()) {
string key = iter.next();
system.out.println(key + ":" + map.get(key));
}
}
}

运行结果如下:

d:aaaaa

c:bbbbb

b:ccccc

a:ddddd

实例扩展:

import java.util.comparator;
import java.util.scanner;
import java.util.treemap;
import problem2.screen;

public class testscreen {
 final static int max_num = 8;
 public static void main(string []args){
  treemap<screen,integer> res = new treemap<screen, integer>(new comparator<screen>() {
   @override
   public int compare(screen screen1, screen t1) { // 定义treemap的排序方法
    return screen1.compareto(t1); // treemap的排序方法是:调用screen的比较方法
   }
  });
  double price, size;
  scanner scan = new scanner(system.in);
  for(int i=0;i<max_num;++i){
   screen screen = new screen();
   size = scan.nextdouble();
   price = scan.nextdouble();
   screen.setsize(size);
   screen.setprice(price);
   res.put(screen,i);
  }
  for(screen screen:res.keyset()){
   screen.show();
  }
  return ;
 }
}
//  测试样例(输入)
//  1 2
//  3 4
//  5 6
//  7 8
//  9 10
//  1 2
//  3 4
//  3 4

到此这篇关于java中使用map排序的实例讲解的文章就介绍到这了,更多相关java如何使用map排序内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关标签: java map排序