如何在 Java 中对 HashMap 进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/780541/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to sort a HashMap in Java
提问by
How are we able to sort a HashMap<key, ArrayList>
?
我们如何才能对 a 进行排序HashMap<key, ArrayList>
?
I want to sort on the basis of a value in the ArrayList
.
我想根据ArrayList
.
回答by Smashery
Without any more information, it's hard to know exactly what you want. However, when choosing what data structure to use, you need to take into account what you need it for. Hashmaps are not designed for sorting - they are designed for easy retrieval. So in your case, you'd probably have to extract each element from the hashmap, and put them into a data structure more conducive to sorting, such as a heap or a set, and then sort them there.
如果没有更多信息,就很难确切地知道您想要什么。但是,在选择要使用的数据结构时,您需要考虑它的用途。Hashmap 不是为排序而设计的——它们是为方便检索而设计的。因此,在您的情况下,您可能必须从哈希图中提取每个元素,并将它们放入更有利于排序的数据结构中,例如堆或集合,然后在那里对它们进行排序。
回答by pgras
Do you have to use a HashMap? If you only need the Map Interface use a TreeMap
你必须使用HashMap吗?如果您只需要 Map Interface,请使用TreeMap
If you want to sort by comparing values in the HashMap. You have to write code to do this, if you want to do it once you can sort the values of your 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());
}
If you want to access this sorted list often, then you could insert your elements into a HashMap<TreeSet<Person>>
, though the semantics of sets and lists are a bit different.
如果您想经常访问这个排序列表,那么您可以将您的元素插入到 a 中HashMap<TreeSet<Person>>
,尽管集合和列表的语义有点不同。
回答by JH.
Seems like you might want a treemap.
看起来你可能想要一个树状图。
http://docs.oracle.com/javase/7/docs/api/java/util/TreeMap.html
http://docs.oracle.com/javase/7/docs/api/java/util/TreeMap.html
You can pass in a custom comparator to it if that applies.
如果适用,您可以将自定义比较器传递给它。
回答by Lars A Fr?yland
If you want to combine a Map for efficient retrieval with a SortedMap, you may use the ConcurrentSkipListMap.
如果您想将 Map 与 SortedMap 结合起来进行高效检索,您可以使用ConcurrentSkipListMap。
Of course, you need the key to be the value used for sorting.
当然,您需要将键作为用于排序的值。
回答by Lars A Fr?yland
http://snipplr.com/view/2789/sorting-map-keys-by-comparing-its-values/
http://snipplr.com/view/2789/sorting-map-keys-by-comparing-its-values/
get the keys
拿到钥匙
List keys = new ArrayList(yourMap.keySet());
Sort them
对它们进行排序
Collections.sort(keys)
print them.
打印它们。
In any case, you can't have sorted values in HashMap (according to 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
].
在任何情况下,您都不能在 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
]。
Though you can push all these values to LinkedHashMap
, for later use as well.
虽然您可以将所有这些值推送到LinkedHashMap
,但也可以供以后使用。
回答by gokhansari
Sorted List by hasmap keys:
按 hasmap 键排序的列表:
SortedSet<String> keys = new TreeSet<String>(myHashMap.keySet());
Sorted List by hashmap values:
按哈希图值排序的列表:
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);
Good Luck!
祝你好运!
回答by Vitalii Fedorenko
In Java 8:
在 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 Guava:
使用番石榴:
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);
回答by Mustafa Güven
Custom compare functionwhich includes functionality for the Turkish alphabetor 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;
}
here is the using example as the following
这是使用示例如下
LinkedHashMap<String, Boolean> ligList = new LinkedHashMap<String, Boolean>();
ligList = sortByKeys(ligList);
回答by Olu Smith
have you considered using a LinkedHashMap<>()..?
你有没有考虑过使用 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
check the sorting part picked from here..
检查从这里挑选的分拣部分..
回答by danywarner
I developed a fully tested working solution. Hope it helps
我开发了一个经过全面测试的工作解决方案。希望能帮助到你
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;
}
}
}