按值对 HashMap 进行排序
问题:
如何根据存储的值对 HashMap 进行排序其中,确保键自动排序为嗯?
解决方案:
泛型方法(Java 8 之前):
实现一个泛型方法来对 a 进行排序地图:
private static <K extends Comparable<K>, V extends Comparable<V>> Map<K, V> sort( final Map<K, V> unsorted, final boolean order) { final var list = new LinkedList<>(unsorted.entrySet()); list.sort((o1, o2) -> order ? o1.getValue().compareTo(o2.getValue()) == 0 ? o1.getKey().compareTo(o2.getKey()) : o1.getValue().compareTo(o2.getValue()) : o2.getValue().compareTo(o1.getValue()) == 0 ? o2.getKey().compareTo(o1.getKey()) : o2.getValue().compareTo(o1.getValue())); return list.stream().collect( Collectors.toMap( Entry::getKey, Entry::getValue, (a, b) -> b, LinkedHashMap::new ) ); }
升序使用和降序:
import java.util.HashMap; import java.util.Map; public class SortMapByValue { public static final boolean ASC = true; public static final boolean DESC = false; public static void main(String[] args) { // Create an unsorted map Map<String, Integer> unsortMap = new HashMap<>(); unsortMap.put("B", 55); unsortMap.put("A", 80); unsortMap.put("D", 20); unsortMap.put("C", 70); // Sort in ascending order Map<String, Integer> sortedMapAsc = sort(unsortMap, ASC); // Sort in descending order Map<String, Integer> sortedMapDesc = sort(unsortMap, DESC); } }
较新的 Java 8 及以上功能:
或者,使用 Java 8 lambda 表达式的更简洁的解决方案:
import java.util.*; import java.util.Map.Entry; import java.util.stream.Collectors; public class SortMapByValue { ... private static Map<String, Integer> sortByValue(Map<String, Integer> unsortMap, final boolean order) { List<Entry<String, Integer>> list = new LinkedList<>(unsortMap.entrySet()); list.sort((o1, o2) -> order ? o1.getValue().compareTo(o2.getValue()) == 0 ? o1.getKey().compareTo(o2.getKey()) : o1.getValue().compareTo(o2.getValue()) : o2.getValue().compareTo(o1.getValue()) == 0 ? o2.getKey().compareTo(o1.getKey()) : o2.getValue().compareTo(o1.getValue())); return list.stream().collect(Collectors.toMap(Entry::getKey, Entry::getValue, (a, b) -> b, LinkedHashMap::new)); } ... }
以上是如何按值对 HashMap 进行排序,同时保持键顺序?的详细内容。更多信息请关注PHP中文网其他相关文章!