[转]利用Java8 stream对Map排序
原文地址:
https://blog.csdn.net/u013719012/article/details/82117477
import java.util.*;
import java.util.stream.Collectors;
public class Main2 {
public static void main(String[] args) {
Map<Integer, String> abcMap = new HashMap<>();
abcMap.put(19, "19");
abcMap.put(14, "14");
abcMap.put(2, "2");
LinkedHashMap<Integer, String> linkedMap = new LinkedHashMap<>();
// 将HashMap转换成LinkedHashMap
abcMap.entrySet().stream().sorted(Map.Entry.comparingByKey())
.forEachOrdered(entry -> linkedMap.put(entry.getKey(), entry.getValue()));
// 如果想要转换成List
List collect = linkedMap.entrySet().stream().map(Map.Entry::getValue).collect(Collectors.toList());
List collect2 = linkedMap.values().stream().collect(Collectors.toList());
List collect3 = new ArrayList<>(linkedMap.values());
for (Object o : collect3) {
System.out.println(o);
}
}
}