Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 对以map作为输入的列表进行排序_Java_List_Sorting - Fatal编程技术网

Java 对以map作为输入的列表进行排序

Java 对以map作为输入的列表进行排序,java,list,sorting,Java,List,Sorting,我有一个列表,其中的元素是map,我想根据map元素值对这个列表进行排序 [{id=45964953, count=1}, {id=46009636, count=1}, {id=45936991, count=1}, {id=45984035, count=2}, {id=45951961, count=1}, {id=45399668, count=31}] 我需要按计数值排序。可以用java实现吗 输出应该是这样的 [ {id=45399668, count=31},{id=45984

我有一个列表,其中的元素是map,我想根据map元素值对这个列表进行排序

[{id=45964953, count=1}, {id=46009636, count=1}, {id=45936991, count=1},  {id=45984035, count=2}, {id=45951961, count=1}, {id=45399668, count=31}]
我需要按计数值排序。可以用java实现吗

输出应该是这样的

[ {id=45399668, count=31},{id=45984035, count=2}, {id=45964953, count=1}, {id=46009636, count=1}, {id=45936991, count=1}, {id=45951961, count=1}]

您可以创建一个类来实现
compariable
(假设
String
Integer
以及映射的键和值),并根据您的条件比较两个映射


然后,您可以将列表和比较器传递给Collections.sort()。

Java8已经发布一段时间了。让你的老师印象深刻:

list = list.stream()
    .sorted((m1, m2) -> Integer.compare(m2.get("count"),m1.get("count")))
    .collect(Collectors.toList());

下面是一些测试代码:

List<Map<String, Integer>> list = new ArrayList<Map<String, Integer>>() {{
    add(new HashMap<String, Integer>() {{put("id",45964953); put("count", 1);}});
    add(new HashMap<String, Integer>() {{put("id",46009636); put("count", 1);}});
    add(new HashMap<String, Integer>() {{put("id",45936991); put("count", 1);}});
    add(new HashMap<String, Integer>() {{put("id",45984035); put("count", 2);}});
    add(new HashMap<String, Integer>() {{put("id",45951961); put("count", 1);}});
    add(new HashMap<String, Integer>() {{put("id",45399668); put("count", 31);}});
}};                      
list = list.stream().sorted((m1, m2) -> Integer.compare(m2.get("count"), m1.get("count"))).collect(Collectors.toList());
System.out.println(list);

拜托,伙计们,使用搜索功能不会那么难。同样的问题在今天(和过去)已经被提出和回答。闻起来像是给我的家庭作业可能的副本看起来很棒,我们目前没有使用Java8,但这肯定是值得寻找的。
[{count=31, id=45399668}, {count=2, id=45984035}, {count=1, id=45964953}, {count=1, id=46009636}, {count=1, id=45936991}, {count=1, id=45951961}]