【问题标题】:Sorting Map keys by the smallest value from a list of integers按整数列表中的最小值对 Map 键进行排序
【发布时间】:2021-06-06 15:19:15
【问题描述】:

我正在尝试对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}) }

排序条件:

  1. 对每个键中的值进行排序
  2. 根据最小值对键进行排序。

【问题讨论】:

    标签: java sorting hashmap java-stream


    【解决方案1】:

    要按字母顺序对键和值按升序排序,您可以执行以下操作:

    如下创建地图:

    SortedMap<String, List<Integer>> a = new TreeMap<>(Collections.reverseOrder());
    

    (i.e., 使用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]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-09
      • 2019-10-14
      • 2021-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多