【问题标题】:Java HashMap sorted by key insertion time - creative order [duplicate]Java HashMap 按键插入时间排序 - 创意顺序 [重复]
【发布时间】:2021-02-24 08:35:25
【问题描述】:

我想按创意顺序对 hashmap 进行排序或将所有键添加到 arraylist 例如:

        HashMap<String, String> map_from_file = new HashMap<String, String>();
        map_from_file.put("C", "c");
        map_from_file.put("B", "b");
        map_from_file.put("D", "d");
        map_from_file.put("A", "a");


        for (String key : map_from_file.keySet()) {
            System.out.println(key);
        }

输出:

A
B
C
D

我希望输出是:

C
B
D
A

感谢您的帮助

【问题讨论】:

    标签: java hashmap


    【解决方案1】:
    Map<String, String> map_from_file = new LinkedHashMap<>();
            map_from_file.put("C", "c");
            map_from_file.put("B", "b");
            map_from_file.put("D", "d");
            map_from_file.put("A", "a");
    
    
            for (String key : map_from_file.keySet()) {
                System.out.println(key);
            }
    

    【讨论】:

      【解决方案2】:

      您必须使用LinkedHashMap 数据结构作为有序键。

      【讨论】:

      • 这可能是一条评论。
      猜你喜欢
      • 2016-06-05
      • 1970-01-01
      • 1970-01-01
      • 2011-08-03
      • 2020-11-28
      • 1970-01-01
      • 2016-01-23
      • 1970-01-01
      • 2018-08-08
      相关资源
      最近更新 更多