可以使用Java 8的新特性来实现按照键值升序或降序排序并返回Map的值。
下面是一个示例代码:
import java.util.HashMap;
import java.util.Map;
public class SortMapByKeys {
public static void main(String[] args) {
Map unsortedMap = new HashMap<>();
unsortedMap.put("d", "fourth");
unsortedMap.put("a", "first");
unsortedMap.put("b", "second");
unsortedMap.put("c", "third");
System.out.println("Unsorted Map: " + unsortedMap);
Map sortedMapByKeyAsc = new HashMap<>();
unsortedMap.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.forEachOrdered(x -> sortedMapByKeyAsc.put(x.getKey(), x.getValue()));
System.out.println("Sorted Map by Key Ascending: " + sortedMapByKeyAsc);
Map sortedMapByKeyDesc = new HashMap<>();
unsortedMap.entrySet().stream()
.sorted(Map.Entry.comparingByKey().reversed())
.forEachOrdered(x -> sortedMapByKeyDesc.put(x.getKey(), x.getValue()));
System.out.println("Sorted Map by Key Descending: " + sortedMapByKeyDesc);
}
}
输出结果为:
Unsorted Map: {a=first, b=second, c=third, d=fourth}
Sorted Map by Key Ascending: {a=first, b=second, c=third, d=fourth}
Sorted Map by Key Descending: {d=fourth, c=third, b=second, a=first}
注意:使用forEachOrdered
方法可以确保结果的顺序是可以预测的,避免在多线程情况下出现可能的并发问题。