一、使用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/zh-hant/n/275901.html