【问题标题】:sorting linked list of Hashmap based on their id key根据 id 键对 Hashmap 的链表进行排序
【发布时间】:2018-03-15 05:54:10
【问题描述】:

我将 HashMap 存储在链接列表中,需要按降序对它们进行排序。下面给出了我的代码

            import java.util.ArrayList;
            import java.util.Comparator;
            import java.util.HashMap;
            import java.util.LinkedList;

            public class Test {


    public static void main(String[] args) {
        LinkedList<HashMap<String,String>> list=new LinkedList<HashMap<String,String>>();

     HashMap<String,String> map=new HashMap<>();
    map.put("id","2");
    map.put("code","200");
    HashMap<String,String> map2=new HashMap<>();
    map2.put("id","1");
    map2.put("code","100");
    HashMap<String,String> map3=new HashMap<>();
    map3.put("id","3");
    map3.put("code","300");
    list.add(map);
    list.add(map2);
    list.add(map3);
    System.out.println("List is::"+list);

    list.sort(Comparator.comparingInt(m -> Integer.parseInt(m.get("id"))));
    System.out.println("list after sorting is::"+list);


    }
}

我想要一个按降序排列的链表,如下所示

            map 3,map, map 2

【问题讨论】:

  • 你试过了吗?而且你的代码中有很多错别字
  • 降序基于什么?你把 3,1,2 放在这里......你的尝试在哪里?
  • 另外,hashmaps 没有排序。链接列表也没有优化为
  • 按什么降序排列?地图中的值?那你为什么首先使用HashMap?上课。
  • LinkedList> list=new LinkedList>(); HashMap map=new HashMap(); map.put("id","2"); map.put("代码","200"); HashMap map2=new HashMap(); map2.put("id","1"); map2.put("代码","100"); HashMap map3=new HashMap(); map3.put("id","3"); map3.put("代码","300");列表。添加(地图); list.add(map2); list.add(map3); System.out.println("列表为::"+list); list.sort(Comparator.comparingInt(m -> Integer.parseInt(m.get("id")))); System.out.println("排序后的列表为::"+list);

标签: java hashmap comparator


【解决方案1】:

您可以使用 TreeMap 并在其构造函数中指定比较器。地图就是这样。但是如果你想对一个 hashmap 的链表进行排序,你可以使用 Collections.sort(list,comparator)。 但这只是残酷的......

【讨论】:

    【解决方案2】:

    Comparator.comparingInt(m -> Integer.parseInt(m.get("id"))

    你必须切换顺序。

     list.sort((firstMap, secondMap) -> Integer.valueOf(secondMap.get("id"))
                .compareTo(Integer.valueOf(firstMap.get("id"))));
    

    【讨论】:

      猜你喜欢
      • 2014-04-27
      • 2011-03-05
      • 2012-09-28
      • 2016-01-21
      • 2012-03-07
      • 1970-01-01
      • 2017-09-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多