【发布时间】: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