如何在Java中对HashMap进行排序

如何在Java中对HashMap进行排序,java,sorting,hashmap,Java,Sorting,Hashmap,我们如何对HashMap进行排序 我想根据ArrayList中的值进行排序,如果没有更多信息,就很难准确地知道您想要什么。但是,在选择要使用的数据结构时,需要考虑它的用途。HashMap不是为排序而设计的-它们是为方便检索而设计的。因此,在您的情况下,您可能必须从hashmap中提取每个元素,并将它们放入更有利于排序的数据结构中,例如堆或集合,然后在那里对它们进行排序。您必须使用hashmap吗?如果您只需要映射界面,请使用 如果要通过比较HashMap中的值进行排序。您必须编写代码来完成此操

我们如何对HashMap进行排序


我想根据
ArrayList

中的值进行排序,如果没有更多信息,就很难准确地知道您想要什么。但是,在选择要使用的数据结构时,需要考虑它的用途。HashMap不是为排序而设计的-它们是为方便检索而设计的。因此,在您的情况下,您可能必须从hashmap中提取每个元素,并将它们放入更有利于排序的数据结构中,例如堆或集合,然后在那里对它们进行排序。

您必须使用hashmap吗?如果您只需要映射界面,请使用


如果要通过比较HashMap中的值进行排序。您必须编写代码来完成此操作,如果您想一次完成此操作,可以对HashMap的值进行排序:

Map<String, Person> people = new HashMap<>();
Person jim = new Person("Jim", 25);
Person scott = new Person("Scott", 28);
Person anna = new Person("Anna", 23);

people.put(jim.getName(), jim);
people.put(scott.getName(), scott);
people.put(anna.getName(), anna);

// not yet sorted
List<Person> peopleByAge = new ArrayList<>(people.values());

Collections.sort(peopleByAge, Comparator.comparing(Person::getAge));

for (Person p : peopleByAge) {
    System.out.println(p.getName() + "\t" + p.getAge());
}
Map people=newhashmap();
人员jim=新人员(“jim”,25岁);
人物斯科特=新人(“斯科特”,28岁);
人物安娜=新人(“安娜”,23);
people.put(jim.getName(),jim);
people.put(scott.getName(),scott);
people.put(anna.getName(),anna);
//尚未分类
List peopleByAge=new ArrayList(people.values());
Collections.sort(peopleByAge,Comparator.comparing(Person::getAge));
用于(人员p:按年龄划分的人员){
System.out.println(p.getName()+“\t”+p.getAge());
}

如果您想经常访问这个排序列表,那么您可以将元素插入到
HashMap
,尽管集合和列表的语义有点不同。

看起来您可能需要一个树映射


如果适用,您可以将自定义比较器传递给它。

如果您想将地图与已分类地图结合起来进行有效检索,可以使用

当然,您需要密钥作为用于排序的值。

拿到钥匙

List keys = new ArrayList(yourMap.keySet());
分类

 Collections.sort(keys)
打印出来

在任何情况下,HashMap中都不能有已排序的值(根据API
,该类不保证映射的顺序;特别是,它不保证顺序随时间保持不变


尽管您可以将所有这些值推送到
LinkedHashMap
,供以后使用。

按hasmap键排序的列表:

SortedSet<String> keys = new TreeSet<String>(myHashMap.keySet());
SortedSet keys=new TreeSet(myHashMap.keySet());
按hashmap值排序的列表:

SortedSet<String> values = new TreeSet<String>(myHashMap.values());
List<String> mapValues = new ArrayList<String>(myHashMap.values());
Collections.sort(mapValues);
SortedSet values=新树集(myHashMap.values());
如果贴图值重复:

SortedSet<String> values = new TreeSet<String>(myHashMap.values());
List<String> mapValues = new ArrayList<String>(myHashMap.values());
Collections.sort(mapValues);
listmapvalues=newarraylist(myHashMap.values());
Collections.sort(映射值);
祝你好运!

在Java 8中:

Comparator<Entry<String, Item>> valueComparator = 
    (e1, e2) -> e1.getValue().getField().compareTo(e2.getValue().getField());

Map<String, Item> sortedMap = 
    unsortedMap.entrySet().stream().
    sorted(valueComparator).
    collect(Collectors.toMap(Entry::getKey, Entry::getValue,
                             (e1, e2) -> e1, LinkedHashMap::new));
比较器值比较器=
(e1,e2)->e1.getValue().getField().compareTo(e2.getValue().getField());
地图分类地图=
unsortedMap.entrySet().stream()。
排序(valueComparator)。
collect(Collectors.toMap)(条目::getKey,条目::getValue,
(e1,e2)->e1,LinkedHashMap::new);
使用:

Map=。。。;
函数getField=新函数(){
公共整数应用(项){
return item.getField();//要排序的字段
}
};
comparatorFunction=Functions.compose(getField,Functions.forMap(map));
comparator=Ordering.natural().onResultOf(comparatorFunction);
Map sortedMap=ImmutableSortedMap.copyOf(Map,comparator);

自定义比较功能,包括土耳其语字母英语以外的其他语言的功能

public <K extends Comparable,V extends Comparable> LinkedHashMap<K,V> sortByKeys(LinkedHashMap<K,V> map){
    List<K> keys = new LinkedList<K>(map.keySet());
    Collections.sort(keys, (Comparator<? super K>) new Comparator<String>() {
        @Override
        public int compare(String first, String second) {
            Collator collator = Collator.getInstance(Locale.getDefault());
            //Collator collator = Collator.getInstance(new Locale("tr", "TR"));
            return collator.compare(first, second);
        }
    });

    LinkedHashMap<K,V> sortedMap = new LinkedHashMap<K,V>();
    for(K key: keys){
        sortedMap.put(key, map.get(key));
    }

    return sortedMap;
}
publicLinkedHashMapSortByKeys(LinkedHashMap地图){
List keys=newlinkedlist(map.keySet());

Collections.sort(keys,(Comparator您考虑过使用LinkedHashMap()吗


检查从..

中挑选的分拣部件。我开发了一个经过充分测试的工作解决方案。希望能有所帮助

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.StringTokenizer;


public class Main {
    public static void main(String[] args) {
    try {
        BufferedReader in = new BufferedReader(new java.io.InputStreamReader           (System.in));
            String str;

        HashMap<Integer, Business> hm = new HashMap<Integer, Business>();
        Main m = new Main();


        while ((str = in.readLine()) != null) {


            StringTokenizer st = new StringTokenizer(str);
            int id = Integer.parseInt(st.nextToken());    // first integer
            int rating = Integer.parseInt(st.nextToken());    // second 

            Business a = m.new Business(id, rating);


            hm.put(id, a);


            List<Business> ranking = new ArrayList<Business>(hm.values());

            Collections.sort(ranking, new Comparator<Business>() {

                public int compare(Business i1, Business i2) {
                    return i2.getRating() - i1.getRating();
                }
            });

            for (int k=0;k<ranking.size();k++) {
                System.out.println((ranking.get(k).getId() + " " + (ranking.get(k)).getRating()));
            }


        }
        in.close();

    } catch (IOException e) {
        e.printStackTrace();
    }


}
public class Business{

    Integer id;
    Integer rating;

    public Business(int id2, int rating2)
    {
        id=id2;
        rating=rating2;

    }

    public Integer getId()
    {
        return id;
    }
    public Integer getRating()
    {
        return rating;
    }


}
}
导入java.io.BufferedReader;
导入java.io.IOException;
导入java.util.ArrayList;
导入java.util.Collections;
导入java.util.Comparator;
导入java.util.HashMap;
导入java.util.List;
导入java.util.StringTokenizer;
公共班机{
公共静态void main(字符串[]args){
试一试{
BufferedReader in=新的BufferedReader(新的java.io.InputStreamReader(System.in));
字符串str;
HashMap hm=新的HashMap();
Main m=新的Main();
而((str=in.readLine())!=null){
StringTokenizer st=新的StringTokenizer(str);
int id=Integer.parseInt(st.nextToken());//第一个整数
int rating=Integer.parseInt(st.nextToken());//秒
业务a=m.新业务(id、评级);
hm.put(id,a);
列表排名=新的ArrayList(hm.values());
Collections.sort(排名,新的比较器(){
公共整数比较(业务i1、业务i2){
返回i2.getRating()-i1.getRating();
}
});

对于(int k=0;k按值排序HashMap:

正如其他人所指出的,HashMaps便于查找,如果您更改它或尝试在映射本身内部排序,您将不再有O(1)查找

您的排序代码如下所示:

class Obj implements Comparable<Obj>{
    String key;
    ArrayList<Integer> val;
    Obj(String key, ArrayList<Integer> val)
    {
    this.key=key;
    this.val=val;
    }
    public int compareTo(Obj o)
    {
     /* Write your sorting logic here. 
     this.val compared to o.val*/
     return 0;
    }
}

public void sortByValue(Map<String, ArrayList<>> mp){

    ArrayList<Obj> arr=new ArrayList<Obj>();
    for(String z:mp.keySet())//Make an object and store your map into the arrayList
    {

        Obj o=new Obj(z,mp.get(z));
        arr.add(o);
    }
    System.out.println(arr);//Unsorted
    Collections.sort(arr);// This sorts based on the conditions you coded in the compareTo function.
    System.out.println(arr);//Sorted
}
class Obj实现了可比较的{
字符串键;
ArrayList val;
Obj(字符串键,ArrayList val)
{
这个。键=键;
这个.val=val;
}
公共国际比较(Obj o)
{
/*在这里写下你的排序逻辑。
与o.val相比,该值为0.val*/
返回0;
}
}
公共无效sortByValue(映射mp){
ArrayList arr=新的ArrayList();
for(String z:mp.keySet())//创建一个对象并将地图存储到arrayList中
{
Obj o=新的Obj(z,mp.get(z));
arr.add(o);
}
System.out.println(arr);//未排序
Collections.sort(arr);//此选项基于在compareTo函数中编码的条件进行排序。
System.out.println(arr);//已排序
}

我开发了一个类,可用于根据键和值对地图进行排序。基本思想是,如果您使用键对地图进行排序,然后创建
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.StringTokenizer;


public class Main {
    public static void main(String[] args) {
    try {
        BufferedReader in = new BufferedReader(new java.io.InputStreamReader           (System.in));
            String str;

        HashMap<Integer, Business> hm = new HashMap<Integer, Business>();
        Main m = new Main();


        while ((str = in.readLine()) != null) {


            StringTokenizer st = new StringTokenizer(str);
            int id = Integer.parseInt(st.nextToken());    // first integer
            int rating = Integer.parseInt(st.nextToken());    // second 

            Business a = m.new Business(id, rating);


            hm.put(id, a);


            List<Business> ranking = new ArrayList<Business>(hm.values());

            Collections.sort(ranking, new Comparator<Business>() {

                public int compare(Business i1, Business i2) {
                    return i2.getRating() - i1.getRating();
                }
            });

            for (int k=0;k<ranking.size();k++) {
                System.out.println((ranking.get(k).getId() + " " + (ranking.get(k)).getRating()));
            }


        }
        in.close();

    } catch (IOException e) {
        e.printStackTrace();
    }


}
public class Business{

    Integer id;
    Integer rating;

    public Business(int id2, int rating2)
    {
        id=id2;
        rating=rating2;

    }

    public Integer getId()
    {
        return id;
    }
    public Integer getRating()
    {
        return rating;
    }


}
}
class Obj implements Comparable<Obj>{
    String key;
    ArrayList<Integer> val;
    Obj(String key, ArrayList<Integer> val)
    {
    this.key=key;
    this.val=val;
    }
    public int compareTo(Obj o)
    {
     /* Write your sorting logic here. 
     this.val compared to o.val*/
     return 0;
    }
}

public void sortByValue(Map<String, ArrayList<>> mp){

    ArrayList<Obj> arr=new ArrayList<Obj>();
    for(String z:mp.keySet())//Make an object and store your map into the arrayList
    {

        Obj o=new Obj(z,mp.get(z));
        arr.add(o);
    }
    System.out.println(arr);//Unsorted
    Collections.sort(arr);// This sorts based on the conditions you coded in the compareTo function.
    System.out.println(arr);//Sorted
}
public static void main(String[] args) {
    Map<String, Integer> unSortedMap = new LinkedHashMap<String, Integer>();
    unSortedMap.put("A", 2);
    unSortedMap.put("V", 1);
    unSortedMap.put("G", 5);
    System.out.println("Unsorted Map :\n");
    for (Map.Entry<String, Integer> entry : unSortedMap.entrySet()) {
        System.out.println(entry.getKey() + "   " + entry.getValue());
    }
    System.out.println("\n");
    System.out.println("Sorting Map Based on Keys :\n");
    Map<String, Integer> keySortedMap = new TreeMap<String, Integer>(unSortedMap);
    for (Map.Entry<String, Integer> entry : keySortedMap.entrySet()) {
        System.out.println(entry.getKey() + "   " + entry.getValue());
    }
    System.out.println("\n");
    System.out.println("Sorting Map Based on Values :\n");
    List<Entry<String, Integer>> entryList = new ArrayList<Entry<String, Integer>>(unSortedMap.entrySet());
    Collections.sort(entryList, new Comparator<Entry<String, Integer>>() {

        @Override
        public int compare(Entry<String, Integer> obj1, Entry<String, Integer> obj2) {
            return obj1.getValue().compareTo(obj2.getValue());
        }
    });
    unSortedMap.clear();
    for (Entry<String, Integer> entry : entryList) {
        unSortedMap.put(entry.getKey(), entry.getValue());
        System.out.println(entry.getKey() + "   " + entry.getValue());
    }
}
package com.edge.collection.map;

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class SortMapByKeyValue {
Map<String, Integer> map = new HashMap<String, Integer>();

public static void main(String[] args) {

    SortMapByKeyValue smkv = new SortMapByKeyValue();
    smkv.createMap();

    System.out.println("After sorting by key ascending order......");
    smkv.sortByKey(true);

    System.out.println("After sorting by key descindeng order......");
    smkv.sortByKey(false);

    System.out.println("After sorting by value ascending order......");
    smkv.sortByValue(true);

    System.out.println("After sorting by value  descindeng order......");
    smkv.sortByValue(false);

}

void createMap() {
    map.put("B", 55);
    map.put("A", 80);
    map.put("D", 20);
    map.put("C", 70);
    map.put("AC", 70);
    map.put("BC", 70);
    System.out.println("Before sorting......");
    printMap(map);
}

void sortByValue(boolean order) {

    List<Entry<String, Integer>> list = new LinkedList<Entry<String, Integer>>(map.entrySet());
    Collections.sort(list, new Comparator<Entry<String, Integer>>() {
        public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
            if (order) {
                return o1.getValue().compareTo(o2.getValue());
            } else {
                return o2.getValue().compareTo(o1.getValue());

            }
        }
    });
    Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
    for (Entry<String, Integer> entry : list) {
        sortedMap.put(entry.getKey(), entry.getValue());
    }
    printMap(sortedMap);

}

void sortByKey(boolean order) {

    List<Entry<String, Integer>> list = new LinkedList<Entry<String, Integer>>(map.entrySet());
    Collections.sort(list, new Comparator<Entry<String, Integer>>() {
        public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
            if (order) {
                return o1.getKey().compareTo(o2.getKey());
            } else {
                return o2.getKey().compareTo(o1.getKey());

            }
        }
    });
    Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
    for (Entry<String, Integer> entry : list) {
        sortedMap.put(entry.getKey(), entry.getValue());
    }
    printMap(sortedMap);
}

public void printMap(Map<String, Integer> map) {
    // System.out.println(map);
    for (Entry<String, Integer> entry : map.entrySet()) {
        System.out.println(entry.getKey() + " : " + entry.getValue());
    }
}
}
Hashmap<Object,Object> items = new HashMap<>();
List<Pair<Object,Object>> items = new ArrayList<>();
HashMap<Integer, Object> map = new HashMap<Integer, Object>();

ArrayList<Integer> sortedKeys = new ArrayList<Integer>(map.keySet());
Collections.sort(sortedKeys, new Comparator<Integer>() {
  @Override
  public int compare(Integer a, Integer b) {
    return a.compareTo(b);
  }
});

for (Integer key: sortedKeys) {
  //map.get(key);
}
public class HashMapSortByValue {
    public static void main(String[] args) {

        HashMap<Long,String> unsortMap = new HashMap<Long,String>();
            unsortMap.put(5l,"B");
            unsortMap.put(8l,"A");
            unsortMap.put(2l, "D");
            unsortMap.put(7l,"C" );

            System.out.println("Before sorting......");
            System.out.println(unsortMap);

            HashMap<Long,String> sortedMapAsc = sortByComparator(unsortMap);
            System.out.println("After sorting......");
            System.out.println(sortedMapAsc);

    }

    public static HashMap<Long,String> sortByComparator(
            HashMap<Long,String> unsortMap) {

            List<Map.Entry<Long,String>> list = new LinkedList<Map.Entry<Long,String>>(
                unsortMap.entrySet());

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

            HashMap<Long,String> sortedMap = new LinkedHashMap<Long,String>();
            for (Entry<Long,String> entry : list) {
              sortedMap.put(entry.getKey(), entry.getValue());
            }
            return sortedMap;
          }

}
public static void main(String[] args) {
    Map<String,String> map = new HashMap<>();

    map.put("b", "dd");
    map.put("c", "cc");
    map.put("a", "aa");

    map = new TreeMap<>(map);

    for (String key : map.keySet()) {
        System.out.println(key+"="+map.get(key));
    }
}