如何在 Java 中对 HashMap 进行排序

我们如何能够排序 HashMap<key, ArrayList>

我想根据 ArrayList中的值进行排序。

443759 次浏览

没有更多的信息,很难知道你到底想要什么。但是,在选择要使用的数据结构时,需要考虑需要它的目的。散列映射不是为排序而设计的——它们是为方便检索而设计的。因此,在您的情况下,您可能必须从散列表中提取每个元素,并将它们放入更有利于排序的数据结构中,比如堆或集,然后在那里对它们进行排序。

Do you have to use a HashMap? If you only need the Map Interface use a 树木地图


如果要通过比较 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());
}

如果希望经常访问这个排序后的列表,那么可以将元素插入到 HashMap<TreeSet<Person>>中,不过集合和列表的语义稍有不同。

看起来你需要一张树图。

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

如果适用,可以向它传入自定义比较器。

如果希望将 Map 与 SortedMap 组合起来进行高效检索,则可以使用 ConcurrentSkipListMap

当然,您需要将键作为用于排序的值。

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

拿钥匙

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

分类

 Collections.sort(keys)

打印出来。

在任何情况下,HashMap 中都不能有已排序的值(根据 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)。

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

按 hasmap 键排序列表:

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

按散列表值排序的列表:

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

In case of duplicated map values:

List<String> mapValues = new ArrayList<String>(myHashMap.values());
Collections.sort(mapValues);

祝你好运!

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

Using 番石榴:

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

自定义比较函数 ,其中包括 土耳其语字母other different languages than english的功能。

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

have you considered using a 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());
}
});
}

results into an organized linked object.

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

检查从 给你中挑选的分类部分。

我开发了一个完全测试的工作解决方案。希望它有所帮助

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




}
}

按值对 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
}

I have developed a class which can be used to sort a map on the basis of keys and values. The basic idea is if you have sort a map using keys then create a TreepMap from your Map which will sort the map by keys. And in case of sorting by values create a list from entrySet and sort the list using comparator interface.

以下是完整的解决方案:

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

正确测试代码:

HashMap 不维护任何顺序,所以如果您想要任何类型的排序,您需要将其存储在其他的东西中,这是一个 map,并且可以有某种排序,比如 LinkedHashMap

下面是一个简单的程序,可以按键、值、升序、降序进行排序。.(如果您修改压缩器,您可以使用任何类型的排序,对键和值)

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

这是 Git 链接

使用成对类将散列表转换为 ArrayList

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

注意,HashMap 本身不能维护排序,正如其他答案所指出的那样。这是一个 大麻映射,散列值是未排序的。因此,您可以在需要的时候对键进行排序,然后按顺序访问值,正如我上面演示的那样,或者您可以找到一个不同的集合来存储您的数据,比如 Pair/Tuples 的 ArrayList,比如 Apache Commons 中找到的 Pair:

Https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/tuple/pair.html

在 Java 中按值对 HashMap 排序:

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