如何在Java中对HashMap进行sorting

我们如何能够sorting一个HashMap<key, ArrayList>

我想根据ArrayList中的值进行sorting。

你必须使用HashMap吗? 如果您只需要Map接口,请使用TreeMap


好吧,我想现在我明白你的问题了,你想通过比较hashMap中的值来sorting。 你必须编写代码来做到这一点,如果你想要这样做,你可以sorting你的哈希值的值:

 Map<String, Person> people = new HashMap<String, Person>(); 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<Person>(people.values()); Collections.sort(peopleByAge, new Comparator<Person>() { public int compare(Person o1, Person o2) { return o1.getAge() - o2.getAge(); } }); for (Person p : peopleByAge) { System.out.println(p.getName() + "\t" + p.getAge()); } 

如果你想经常访问这个sorting列表,那么你应该插入你的元素在哈希映射一个有序的集(例如TreeSet)…

通过hasmap键sorting:

 SortedSet<String> keys = new TreeSet<String>(myHashMap.keySet()); 

按散列表值sorting:

 SortedSet<String> values = new TreeSet<String>(myHashMap.values()); 

祝你好运!

http://snipplr.com/view/2789/sorting-map-keys-by-comparing-its-values/

拿钥匙

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

sorting他们

  Collections.sort(keys) 

打印它们。

在任何情况下,您都不能在HashMap中对值进行sorting(根据API, This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time )。

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

看起来像你可能想要一个树形图。

http://docs.oracle.com/javase/7/docs/api/java/util/TreeMap.html

如果适用的话,你可以传入一个自定义的比较器。

自定义比较function ,包括土耳其字母表其他不同于英语的语言的function

 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; } 

下面是使用示例

 LinkedHashMap<String, Boolean> ligList = new LinkedHashMap<String, Boolean>(); ligList = sortByKeys(ligList); 

在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)); 

使用番石榴 :

 Map<String, Item> map = ...; Function<Item, Integer> getField = new Function<Item, Integer>() { public Integer apply(Item item) { return item.getField(); // the field to sort on } }; comparatorFunction = Functions.compose(getField, Functions.forMap(map)); comparator = Ordering.natural().onResultOf(comparatorFunction); Map<String, Item> sortedMap = ImmutableSortedMap.copyOf(map, comparator); 

没有更多的信息,很难确切地知道你想要什么。 但是,在select要使用的数据结构时,需要考虑您需要的数据结构。 散列图并不是为sorting而devise的 – 它们被devise为易于检索。 所以在你的情况下,你可能需要从hashmap中提取每个元素,并把它们放到一个更有利于sorting的数据结构中,比如堆或者集合,然后在那里sorting。

如果您想将一个Map与一个SortedMap进行高效检索,可以使用ConcurrentSkipListMap 。

当然,你需要的关键是用于sorting的价值。

你有没有考虑使用LinkedHashMap <>()..?

  public static void main(String[] args) { Map<Object, Object> handler = new LinkedHashMap<Object, Object>(); handler.put("item", "Value"); handler.put(2, "Movies"); handler.put("isAlive", true); for (Map.Entry<Object, Object> entrY : handler.entrySet()) System.out.println(entrY.getKey() + ">>" + entrY.getValue()); List<Map.Entry<String, Integer>> entries = new ArrayList<Map.Entry<String, Integer>>(); Collections.sort(entries, new Comparator<Map.Entry<String, Integer>>() { public int compare(Map.Entry<String, Integer> a, Map.Entry<String, Integer> b) { return a.getValue().compareTo(b.getValue()); } }); } 

结果到一个有组织的链接对象。

  item>>Value 2>>Movies isAlive>>true 

检查从这里挑选的分拣部分..

这可能是你在找什么。 它显示了如何使用TreeMap和自定义比较器来完成工作。

按值sortingHashMap:

正如其他人指出的那样。 如果你改变它,或者尝试在地图内进行sorting,你将不再需要O(1)查找。

您的sorting代码如下所示:

 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 } 

我开发了一个完全testing的工作解决 希望它有帮助

 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; } } } 

我已经开发了一个类,可以使用键和值的基础上sorting地图。 基本的想法是,如果您使用键sorting地图,然后从您的地图创build一个TreePMap,它将按键sorting地图。 如果按值sorting,则从entrySet中创build一个列表,并使用比较器接口对列表进行sorting。

这是完整的解决scheme:

 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()); } } 

代码正确testing:D