我正在尝试HashMap
如下排序
HashMap<String, List<obj> a = new hashmap<>();
a.put('a',{8,10,9});
a.put('b',{6,9,1});
排序输出就像
{ ('b',{1,6,9}) , ('a',{8,9,10}) }
分拣条件:
- 对每个键中的值进行排序
- 根据最小值对键进行排序。
我正在尝试HashMap
如下排序
HashMap<String, List<obj> a = new hashmap<>();
a.put('a',{8,10,9});
a.put('b',{6,9,1});
排序输出就像
{ ('b',{1,6,9}) , ('a',{8,9,10}) }
分拣条件:
要按字母顺序对键和值按升序排序,您可以执行以下操作:
创建地图如下:
SortedMap<String, List<Integer>> a = new TreeMap<>(Collections.reverseOrder());
(即,使用SortedMap)获取按降序排序的键,并使用Collection.sort分别对值进行排序。
例如:
public static void main(String[] args) {
SortedMap<String, List<Integer>> a = new TreeMap<>(Collections.reverseOrder());
List<Integer> x = new ArrayList<>(List.of(8, 10, 9));
List<Integer> y = new ArrayList<>(List.of(6, 9, 1));
a.put("a", x);
a.put("b", y);
a.forEach((k, v) -> Collections.sort(v));
a.forEach((k, v) -> System.out.println(k + " - "+ v ));
}
输出:
b - [1, 6, 9]
a - [8, 9, 10]
要按最小值对键进行排序,可以创建一种方法来排序Map
,如下所示:
public static Map<String, List<Integer>> sortByMinimalValue(Map<String, List<Integer>> m){
List<Map.Entry<String, List<Integer>>> list = new ArrayList<>(m.entrySet());
m.forEach((k, v) -> Collections.sort(v));
list.sort(Comparator.comparingInt(o -> Collections.min(o.getValue())));
Map<String, List<Integer>> sortedMap = new LinkedHashMap<>();
list.forEach(aa -> sortedMap.put(aa.getKey(), aa.getValue()));
return sortedMap;
}
完整示例:
public static void main(String[] args) {
List<Integer> x = new ArrayList<>(List.of(8, 10, 9));
List<Integer> y = new ArrayList<>(List.of(6, 9, 1));
List<Integer> z = new ArrayList<>(List.of(2, 5, 7));
Map<String, List<Integer>> a = Map.of("a", x, "b", y, "c", z);
sortByMinimalValue(a).forEach((k, v) -> System.out.println(k + " - "+ v ));
}
输出:
b - [1, 6, 9]
c - [2, 5, 7]
a - [8, 9, 10]