如何给Map<String, Object> map排序,排序依据是map.get("count")
时间: 2024-04-17 13:25:17 浏览: 13
您可以使用Java中的`Stream`和`Comparator`来对`Map<String, Object>`进行排序。以下是一个示例代码:
```java
import java.util.*;
public class Main {
public static void main(String[] args) {
Map<String, Object> map = new HashMap<>();
map.put("A", 5);
map.put("B", 2);
map.put("C", 7);
map.put("D", 1);
List<Map.Entry<String, Object>> sortedList = new ArrayList<>(map.entrySet());
// 使用Comparator进行排序
sortedList.sort(Comparator.comparingInt(entry -> (int) entry.getValue()));
// 打印排序后的结果
for (Map.Entry<String, Object> entry : sortedList) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
```
在上面的代码中,我们首先将`Map<String, Object>`转换为`List<Map.Entry<String, Object>>`,然后使用`Comparator.comparingInt()`方法指定排序依据为`map.get("count")`。最后,我们通过遍历排序后的列表来打印结果。
请注意,这里假设`map.get("count")`返回的是一个整数类型。如果返回的是其他类型,需要相应地修改比较器的逻辑。