I have a HashMap that contains a list of users and the key is the id of the team that this user participates. The set of keys looks like this:
我有一个包含用户列表的HashMap,密钥是该用户参与的团队的ID。这组键看起来像这样:
[59b83da60b616d17065a993a, null, 59b84145cb49632609e03811, 59a82440cc32316561d803ce, 59c109aa20fe7b48f3832eef, 59a74647cc32316561d7be21, 59c5013b20fe7b48f3871c83]
Taking into consideration that every team has an ID and a name, I would like to know how can I sort this HashMap by the corresponding names if these IDs and keeping the field null
in the first position of the HashMap.
考虑到每个团队都有一个ID和一个名称,我想知道如何通过相应的名称对这个HashMap进行排序,如果这些ID并将字段保留在HashMap的第一个位置。
I have a list of teams where I could easily check what is the name of a team with the ID "1" using the method getName(String id)
. But my difficulty is to deal with the HashMap.
我有一个团队列表,我可以使用getName(String id)方法轻松检查ID为“1”的团队的名称。但我的困难是处理HashMap。
1 个解决方案
#1
3
If your want to sort your map, you should not use HashMap
, use some SortedMap
like TreeMap
instead. You can typically initialize such maps with a comparator to specify the sorting order. Something like:
如果你想对你的地图进行排序,你不应该使用HashMap,而是使用像TreeMap这样的SortedMap。您通常可以使用比较器初始化此类映射以指定排序顺序。就像是:
Map<String, Team> teams = new TreeMap<>(Comparator.nullsFirst(Comparator.naturalOrder()));
#1
3
If your want to sort your map, you should not use HashMap
, use some SortedMap
like TreeMap
instead. You can typically initialize such maps with a comparator to specify the sorting order. Something like:
如果你想对你的地图进行排序,你不应该使用HashMap,而是使用像TreeMap这样的SortedMap。您通常可以使用比较器初始化此类映射以指定排序顺序。就像是:
Map<String, Team> teams = new TreeMap<>(Comparator.nullsFirst(Comparator.naturalOrder()));