import java.util.*;
public class MapSortExample {
public static void main(String[] args) {
// 原始的待排序的 Map
Map<String, Integer> map = new HashMap<>();
map.put("apple", 5);
map.put("banana", 2);
map.put("orange", 8);
map.put("grape", 1);
// 对 Map 的键值对按值进行排序
List<Map.Entry<String, Integer>> sortedList = new ArrayList<>(map.entrySet());
sortedList.sort(Map.Entry.comparingByValue());
// 遍历排序后的键值对
for (Map.Entry<String, Integer> entry : sortedList) {
System.out.println(entry.getKey() + " - " + entry.getValue());
}
}
}
以上代码输出的结果将会是:
在示例代码中,我们创建了一个原始的待排序的 Map,并将键值对放入其中。然后,我们将 Map 的键值对转换为 List<Map.Entry<String, Integer>> 类型,并使用 sortedList.sort(Map.Entry.comparingByValue()) 对键值对按值进行排序。最后,我们使用 for-each 循环遍历排序后的键值对,并输出结果。
grape - 1
banana - 2
apple - 5
orange - 8
注:
通过这种方式,你可以在 Java 8 中对 Map 进行排序。请注意,这种方式并不会修改原始的 Map,而是返回一个新的排序后的键值对列表。
JAVA 8 排序
1.按键排序:
import java.util.*;
public class Main {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("three", 3);
map.put("one", 1);
map.put("four", 4);
map.put("two", 2);
Map<String, Integer> sortedMap = new LinkedHashMap<>();
map.entrySet()
.stream()
.sorted(Map.Entry.comparingByKey())
.forEachOrdered(e -> sortedMap.put(e.getKey(), e.getValue()));
sortedMap.forEach((k, v) -> System.out.println(k + ": " + v));
}
}
2按值排序:
import java.util.*;
public class Main {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("three", 3);
map.put("one", 1);
map.put("four", 4);
map.put("two", 2);
List<Map.Entry<String, Integer>> entries = new ArrayList<>(map.entrySet());
entries.sort(Map.Entry.comparingByValue());
Map<String, Integer> sortedMap = new LinkedHashMap<>();
for (Map.Entry<String, Integer> entry : entries) {
sortedMap.put(entry.getKey(), entry.getValue());
}
sortedMap.forEach((k, v) -> System.out.println(k + ": " + v));
}
}