从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
);
转换为 ArrayList
List<Double> arrayList = map.values()
.stream()
.collect(
Collectors.toCollection(ArrayList::new)
)
输出结果:[7351.03, 2348.26, 1234.86, 8956.31, 1015.45]
按升序排列的排序数组列表
List<Double> arrayListSortedAsc = map.values()
.stream()
.sorted()
.collect(
Collectors.toCollection(ArrayList::new)
);
输出: [1015.45, 1234.86, 2348.26, 7351.03, 8956.31]
转换为降序排列的 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]
转换为 HashSet
Set<Double> hashSet = map.values()
.stream()
.collect(
Collectors.toCollection(HashSet::new)
);
输出:[2348.26,8956.31,1015.45,1234.86,7351.03]
转换为优先队列
PriorityQueue<Double> priorityQueue = map.values()
.stream()
.collect(
Collectors.toCollection(PriorityQueue::new)
)
输出: [1015.45, 1234.86, 2348.26, 8956.31, 7351.03]
参考资料
Java - 包 java.util.stream
Java - 包 java.util
TreeBidiMap
是一个OrderedMap
,顺序应该没问题。问题所需的排序是基于值而不是键。 - Vlasec