Java 8 以上...
您可以使用 Streams 和 Collectors.toCollection() 将 Collection 转换为任何集合(即 List、Set 和 Queue)。
考虑以下示例地图
Map<Integer, Double> map = Map.of(
1, 1015.45,
2, 8956.31,
3, 1234.86,
4, 2348.26,
5, 7351.03
);
到数组列表
List<Double> arrayList = map.values()
.stream()
.collect(
Collectors.toCollection(ArrayList::new)
);
输出:[7351.03, 2348.26, 1234.86, 8956.31, 1015.45]
到 Sorted ArrayList(升序)
List<Double> arrayListSortedAsc = map.values()
.stream()
.sorted()
.collect(
Collectors.toCollection(ArrayList::new)
);
输出:[1015.45, 1234.86, 2348.26, 7351.03, 8956.31]
到 Sorted ArrayList(降序)
List<Double> arrayListSortedDesc = map.values()
.stream()
.sorted(
(a, b) -> b.compareTo(a)
)
.collect(
Collectors.toCollection(ArrayList::new)
);
输出:[8956.31、7351.03、2348.26、1234.86、1015.45]
到链表
List<Double> linkedList = map.values()
.stream()
.collect(
Collectors.toCollection(LinkedList::new)
);
输出:[7351.03, 2348.26, 1234.86, 8956.31, 1015.45]
到哈希集
Set<Double> hashSet = map.values()
.stream()
.collect(
Collectors.toCollection(HashSet::new)
);
输出:[2348.26, 8956.31, 1015.45, 1234.86, 7351.03]
到 PriorityQueue
PriorityQueue<Double> priorityQueue = map.values()
.stream()
.collect(
Collectors.toCollection(PriorityQueue::new)
);
输出:[1015.45、1234.86、2348.26、8956.31、7351.03]
参考
Java - Package java.util.stream
Java - Package java.util