Java排序图按键说明 [英] Java Sort map by key explanation
问题描述
我最近发现了一种对包含GregorianCalendar作为键的地图进行排序的好方法.
I recently found a great way to sort a map that contains GregorianCalendar as keys.
Map<GregorianCalendar, String> map = new HashMap<>();
Map<GregorianCalendar, String> sortedMap = map.entrySet().stream().sorted(Map.Entry.comparingByKey()).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(oldValue, newValue) -> oldValue, LinkedHashMap::new));
有人可以帮助我理解此命令中调用的每个过程,尤其是从流函数进行的过程吗?
Can someone help me to understand each procedure called in this command especially going on from the stream function ?
谢谢
推荐答案
map.entrySet().stream()
生成输入Map
的条目(即Stream<Map.Entry<GregorianCalendar,String>>
.)的Stream
.
map.entrySet().stream()
produces a Stream
of the entries of the input Map
(i.e. a Stream<Map.Entry<GregorianCalendar,String>>
.
.sorted(Map.Entry.comparingByKey())
通过条目的键对Stream
的元素进行排序(这取决于键类型-GregorianCalendar
-实现Comparable
的事实).
.sorted(Map.Entry.comparingByKey())
sorts the elements of this Stream
by the keys of the entries (it relies on the fact that the key type - GregorianCalendar
- implements Comparable
).
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(oldValue, newValue) -> oldValue, LinkedHashMap::new))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(oldValue, newValue) -> oldValue, LinkedHashMap::new))
生成一个LinkedHashMap
,其中包含与输入Map
相同的条目.由于使用的是LinkedHashMap
,因此将保持插入顺序,并且由于通过键对Stream
的条目进行了排序,因此会得到一个Map
,其插入顺序(和迭代顺序)是根据LinkedHashMap
的顺序排列的.键.
produces a LinkedHashMap
that contains the same entries as the input Map
. Since you are using LinkedHashMap
, the insertion order is maintained, and since you sorted the entries of the Stream
by the keys, you get a Map
whose insertion order (and iteration order) is according to the order of the keys.
当然,通过将输入Map
的所有条目放在TreeMap
中,您可以更轻松地获得排序的Map
:
Of course you can get a sorted Map
more easily by putting all the entries of the input Map
in a TreeMap
:
Map<GregorianCalendar, String> sortedMap = new TreeMap<>(map);
即使将新条目添加到Map
,这也可以保持顺序.
This has the advantage of maintaining the order even if you add new entries to the Map
.
这篇关于Java排序图按键说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!