我有一个列表,作为地图的元素,我想在地图元素值
上对此列表进行排序[{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}]
答案 0 :(得分:1)
您可以创建一个实现Comparable<Map<String,Integer>>
的类(假设String
和Integer
以及地图的键和值),并根据您的条件比较两个地图。
然后您可以将列表和比较器传递给Collections.sort()。
答案 1 :(得分:1)
Java 8已经有一段时间了。用这个打动你的老师:
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);
输出:
[{count=31, id=45399668}, {count=2, id=45984035}, {count=1, id=45964953}, {count=1, id=46009636}, {count=1, id=45936991}, {count=1, id=45951961}]