按值對 Hashmap 進行排序
問題:
問題:我們需要根據值對 HashMap進行排序它包含的值,並在期間維護鍵值對
解決方案:自訂版本:排序方法的定製版本可以是創建,允許特定的升序或降序值排序。
範例實作: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 SortMapByValue { public static final boolean ASC = true; public static final boolean DESC = false; public static void main(String[] args) { // Create dummy HashMap Map<Integer, String> unsortedMap = new HashMap<>(); unsortedMap.put(1, "froyo"); unsortedMap.put(2, "abby"); unsortedMap.put(3, "denver"); unsortedMap.put(4, "frost"); unsortedMap.put(5, "daisy"); // Sort in ascending order Map<Integer, String> sortedMapAsc = sortByValue(unsortedMap, ASC); // Sort in descending order Map<Integer, String> sortedMapDesc = sortByValue(unsortedMap, DESC); // Print sorted maps System.out.println("Sorted Ascending:"); printMap(sortedMapAsc); System.out.println("Sorted Descending:"); printMap(sortedMapDesc); } private static Map<Integer, String> sortByValue(Map<Integer, String> map, boolean order) { List<Entry<Integer, String>> list = new LinkedList<>(map.entrySet()); // Custom comparator for values Collections.sort(list, new Comparator<Entry<Integer, String>>() { public int compare(Entry<Integer, String> o1, Entry<Integer, String> o2) { if (order) { return o1.getValue().compareTo(o2.getValue()); } else { return o2.getValue().compareTo(o1.getValue()); } } }); // Return sorted LinkedHashMap Map<Integer, String> sortedMap = new LinkedHashMap<>(); for (Entry<Integer, String> entry : list) { sortedMap.put(entry.getKey(), entry.getValue()); } return sortedMap; } public static void printMap(Map<Integer, String> map) { for (Entry<Integer, String> entry : map.entrySet()) { System.out.println(entry.getKey() + " - " + entry.getValue()); } System.out.println(); } }
以上是如何在 Java 中按值對 HashMap 進行排序,同時保留鍵值對?的詳細內容。更多資訊請關注PHP中文網其他相關文章!