一、使用Collections的sort方法
Java的Collections类中提供了一个sort方法可以对List进行排序。所以可以将HashMap中的键值对存放到List中,然后根据值进行排序,最后将排好序的键值对再放回HashMap中。
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
public class SortHashMapByValue {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("apple", 8);
map.put("banana", 5);
map.put("pear", 3);
map.put("watermelon", 2);
List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(map.entrySet());
Collections.sort(list, new Comparator<Entry<String, Integer>>() {
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
return o2.getValue().compareTo(o1.getValue());
}
});
HashMap<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
for (Entry<String, Integer> entry : list) {
sortedMap.put(entry.getKey(), entry.getValue());
}
System.out.println(sortedMap);
}
}
二、使用Stream API
Java 8中提供了Stream API,可以通过对HashMap进行操作来对键值对进行处理。可以使用Stream中的sorted方法来对值进行排序,最后将排好序的键值对放回HashMap中。
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map.Entry;
import java.util.stream.Collectors;
public class SortHashMapByValue {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("apple", 8);
map.put("banana", 5);
map.put("pear", 3);
map.put("watermelon", 2);
HashMap<String, Integer> sortedMap = map.entrySet().stream()
.sorted(Entry.comparingByValue())
.collect(Collectors.toMap(Entry::getKey, Entry::getValue,
(e1, e2) -> e1, LinkedHashMap::new));
System.out.println(sortedMap);
}
}
三、使用PriorityQueue
Java中提供了PriorityQueue来生成一个优先级队列,使用优先级队列可以对HashMap的值进行排序。先将HashMap中的键值对放入优先级队列,然后遍历队列,取出排好序的键值对,最后将排好序的键值对再放回HashMap中。
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map.Entry;
import java.util.PriorityQueue;
public class SortHashMapByValue {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("apple", 8);
map.put("banana", 5);
map.put("pear", 3);
map.put("watermelon", 2);
PriorityQueue<Entry<String, Integer>> pq = new PriorityQueue<Entry<String, Integer>>(
new Comparator<Entry<String, Integer>>() {
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
return o2.getValue().compareTo(o1.getValue());
}
});
for (Entry<String, Integer> entry : map.entrySet()) {
pq.offer(entry);
}
HashMap<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
while (!pq.isEmpty()) {
Entry<String, Integer> entry = pq.poll();
sortedMap.put(entry.getKey(), entry.getValue());
}
System.out.println(sortedMap);
}
}
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/275901.html
微信扫一扫
支付宝扫一扫