Java中Map根据键值(key)或者值(value)进行排序实现

我们都知道,java中的Map结构是key->value键值对存储的,而且根据Map的特性,同一个Map中 不存在两个Key相同的元素,而value不存在这个限制。换句话说,在同一个Map中Key是唯一的,而value不唯一。Map是一个接口,我们不能 直接声明一个Map类型的对象,在实际开发中,比较常用的Map性数据结构是HashMap和TreeMap,它们都是Map的直接子类。如果考虑到存取 效率的话,建议使用HashMap数据结构,而如果需要考虑到Key的顺序,建议使用TreeMap,但是TreeMap在删除、添加过程中需要排序,性能比较差。

1 、 以Key进行排序
我们可以声明一个TreeMap对象

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

然后往map中添加元素,可以通过输出结果,可以发现map里面的元素都是排好序的

//遍历集合for (Iterator<Integer> it = map.keySet().iterator(); it.hasNext();) {Person person = map.get(it.next());System.out.println(person.getId_card() + " " + person.getName());}

我们也可以声明一个HashMap对象,然后把HashMap对象赋值给TreeMap,如下:

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

2、以Value进行排序
先声明一个HashMap对象:

Map<String, Integer> map = new HashMap<String, Integer>();

然后我们可以将Map集合转换成List集合中,而List使用ArrayList来实现如下:

List<Entry<String,Integer>> list =new ArrayList<Entry<String,Integer>>(map.entrySet());

最后通过Collections.sort(List l, Comparator c)方法来进行排序,代码如下:

Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {public int compare(Map.Entry<String, Integer> o1,Map.Entry<String, Integer> o2) {return (o2.getValue() - o1.getValue());}});

上述代码是讲map中的value按照逆序排序,如果需要按照升序进行排序的话,只需要修改o2.getValue() – o1.getValue()为o1.getValue() – o2.getValue()即可

“Java中Map根据键值(key)或者值(value)进行排序实现”的1,464个回复

  1. I think if you look at my agenda, it s pretty damn strong cialis 20 mg Due to the proximity of the underlying sciatic nerve, caution should be taken if administering FASLODEX at the dorsogluteal injection site see WARNINGS AND PRECAUTIONS and ADVERSE REACTIONS

  2. Excellent blog here! Also your website rather a lot up fast!
    What web host are you the usage of? Can I get your
    affiliate hyperlink for your host? I wish my site loaded
    up as fast as yours lol

  3. Total de Gols no Torneio, Total de Gols do Time, Time com Mais Gols – Para os mercados que se aplicam a todo o torneio, os gols marcados nos 90 minutos ou no tempo extra contarГЈo. Para os mercados que se referem a um determinado conjunto de dispositivos elГ©tricos em uma determinada data(s), apenas gols nos 90 minutos contam. Gols marcados na disputa de pГЄnaltis nГЈo contam. Se um jogo for adiado, o Total de gols (para um grupo de jogos em uma determinada data(s)) serГЎ anulado. O menu Г© longo, e cada tipo de aposta Г© chamado de “mercado”. As opГ§Гµes incluem desde adivinhar o placar de cada jogo (exato, por total de gols etc.), as equipes que serГЈo classificadas para as seguintes fases, atГ© acertar quem vai dominar o primeiro tempo e quem vai ganhar ao final do jogo, por exemplo.
    https://lorenzoblub221081.blogminds.com/resultado-do-jogo-de-jogo-de-hoje-13916209
    Na noite desta sexta-feira, 11 de novembro, no campo do Eucalipal, ocorreu pela segunda vez na competiГ§ГЈo deste ano a utilizaГ§ГЈo de atleta irregular na 17ВЄ ediГ§ГЈo da Copa do Futuro. Em partida realizada na categoria Sub- 15, os clubes do Ideal e Arena TM se enfrentaram com placar final de 3×1 para o Ideal, porГ©m, o que todos nГЈo esperavam Г© que a equipe vencedora colocou um atleta irregular, infringindo as regras do regulamento da competiГ§ГЈo, que cita exclusГЈo da equipe nessas condiГ§Гµes. Na noite desta sexta-feira, 11 de novembro, no campo do Eucalipal, ocorreu pela segunda vez na competiГ§ГЈo deste ano a utilizaГ§ГЈo de atleta irregular na 17ВЄ ediГ§ГЈo da Copa do Futuro. Em partida realizada na categoria Sub- 15, os clubes do Ideal e Arena TM se enfrentaram com placar final de 3×1 para o Ideal, porГ©m, o que todos nГЈo esperavam Г© que a equipe vencedora colocou um atleta irregular, infringindo as regras do regulamento da competiГ§ГЈo, que cita exclusГЈo da equipe nessas condiГ§Гµes.

  4. Don’t let your house sit on the market for months or accept a low-ball offer. Get an offer from Home Cash Guys right away, and sell your home in 30 days or less. All you have to do is call or fill out this form to get started. Real estate agent Ken D’Angelo founded HomeVestors of America in 1989 and began franchising in 1996. By the end of that year, it had 17 franchisees and generated about $800,000 in revenue. It also sold its 25,000th house, in Jonesboro, GA. Franchisees hold the homes for six months on average. Home buyers who do mortgage loan shopping can avoid leaving money on the table. The importance of credit in building new businesses, and what you should know before you borrow money. We provide a step-by-step instruction on the various ways you can establish credit. 1) Establish your personal credit. “For a new business, it’s your personal credit that matters,” said Chris Dlugozima, a certified consumer credit counselor at the
    https://research-wiki.win/index.php?title=Townhouses_for_rent_by_owner_near_me
    If you have any questions about foreclosures in Boca Raton or any other area listed above, please don’t hesitate to contact me or call at (561) 866-7584 and I will get back to you soon. The servicer will send a notice about the resolution conference to you. To participate in the program, you have to, among other things, agree to the meeting, meet with a housing counselor beforehand (unless you can’t get an appointment before the conference), and pay a fee. The conference will occur within 75 days after the lender sends the notice. (Or. Rev. Stat. § 86.729). As of last Friday, the total number of mortgages still in forbearance stood at 890,000. Those who remain in forbearance still have the chance to work out a suitable plan with the servicing company that represents their lender. And the servicing companies are under pressure to do just that by both federal and state agencies.