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)进行排序实现”的5,862个回复

  1. cannabis seeds Gorilla Glue Auto is one of the best yielding autoflower strains that produces amazing yields of up to 600g m 2oz ft indoors and 800g plant 28,2oz outdoors. Since there are over 2,000 cannabis strains on the website, you should find that the company has almost anything you want. You will need to carefully check out online weed stores for the red flags listed above.

  2. russia will not stop its war in Ukraine. It is confirmed by Kremlin. It’s time to be UKRAINIAN! Ask NATO to close the sky. #NoFlyZoneUA #Stoprussia

    Mariupol. Direct strike of Russian troops at the maternity hospital. People, children are under the wreckage. Atrocity! How much longer will the world be an accomplice ignoring terror? Close the sky right now! Stop the killings! You have power but you seem to be losing humanity.

    March 9
    Russian losses starting from Russian full scale invasion in Ukraine:

    > 12000 Manpower
    116 Captives
    49+1 Aircraft
    81+1 Helicopters
    317+14 Tanks
    1070+34 Armoured fighting vehicles
    120 Artillery
    28+1 Air defense systems
    56 Multiple rocket launchers
    60 Tankers
    7+ Tactical unmanned aircraft
    3+ Boats
    482++8 Automotive equipment

  3. Self-Imрrovement and succеss go hаnd in hand. Tаking the stерs tо make уourself а bеttеr and mоre wеll-rounded individual will provе to be a wise dеcision. https://thoughtoftheday.btcfreedom.design
    Thе wise рersоn fееls the раin of оnе аrrow. The unwisе fееls thе pain of twо.
    Whеn lооking fоr wise wоrds, the best ones оften come from оur еldеrs.
    Yоu’ve hеаrd thаt it’s wisе tо lеarn frоm еxрeriеnce, but it is wisеr to lеаrn from the exрeriеnce of othеrs.
    We tend to think оf greаt thinkеrs аnd innоvаtоrs as sоlоists, but thе truth is thаt the greatеst innovativе thinking doеsn’t occur in a vacuum. Innovatiоn results from collаbоrаtion.
    Somе of us think holding оn makеs us strоng, but somеtimes it is letting gо.
    But what I’vе discoverеd over time is that sоmе of thе wisеst pеoрle I knоw hаve alsо bеen sоmе оf thе most brоkеn pеоple.
    Dоn’t wаste уоur time with exрlanatiоns, реoрlе onlу hеar what thеу wаnt tо heаr.
    To mаke difficult decisiоns wiselу, it helps to hаvе a sуstеmatic process fоr аssеssing eаch choicе and its consеquencеs – the potеntiаl impact on еаch aspect of уour lifе.
    Each оf us еxpеriencеs dеfeats in life. Wе cаn trаnsform dеfеаt intо victorу if we lеаrn frоm life’s whuррings.

  4. Идеи с целью женитьбы во Москве. Увлекательные мысли согласно проведению женитьбы. Креативный аспект ко компании брачного праздника создаст существенное явление во Вашей существования запоминающимся! https://anikolsky.com свадебная подготовка

  5. For Players who want access to less known lotteries and other games. Through these three schemes, the real estate sector and the economy of the state will be boosted amid the covid-19 pandemic. Now, from the SuperEnaLotto page, choose 6 numbers between 1 and 90 for each ticket. https://masterfrenchonline.com/?p=1968