按值对 Hashmap 进行排序
问题:
我们需要根据值对 HashMap 进行排序它包含的值,并在期间维护键值对
解决方案:
按值对 HashMap 进行排序可以使用通用方法来完成。以下步骤概述了该过程:
示例实现:
以下 Java 代码实现排序算法:
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中文网其他相关文章!