map怎么遍历value(Map根据keyvalue分别排序)
map怎么遍历value(Map根据keyvalue分别排序)
代码片段
public static void main(String[] args) {
Map<String String> map = new HashMap<>();
map.put("b" "b");
map.put("d" "d");
map.put("c" "c");
// 按key排序
Set<String> set = map.keySet();
Object [] arr = set.toArray();
Arrays.sort(arr);
for (Object str : arr) {
System.out.println(str);
}
// 按value排序
List<Map.Entry<String String>> entries = new ArrayList<>(map.entrySet());
Collections.sort(entries Comparator.comparing(Map.Entry::getValue));
for (Map.Entry<String String> m : entries) {
System.out.println(m.getValue());
}
}