我将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
您可以使用树状图并在其构造函数中指定比较器。这就是地图呢。但是如果你想对哈希图的链表进行排序,你可以使用 Collections.sort(list, comparator(。但这太残酷了...
Comparator.comparingInt(m -> Integer.parseInt(m.get("id"((
你必须切换顺序。
list.sort((firstMap, secondMap) -> Integer.valueOf(secondMap.get("id"))
.compareTo(Integer.valueOf(firstMap.get("id"))));