如何使用比较器将 HashMap 转换为 TreeMap?
How to convert a HashMap to a TreeMap using a comparator?
在我的代码中有以下 HashMap
,其中 key
是一个 Kennel 对象,value
是该 kennel 中的 Dog 对象列表。
填充 HashMap
后,我可以将其转换为 Treemap
并传入比较器吗?
Map<Kennel, List<Dog>> mapOfKennelsAndDogs;
//populate the map
//convert it to a treemap?
只需使用比较器创建树状图,然后添加所有条目。
Comparator<Kennel> ordering = ...;
TreeMap<Kennel, List<Dog>> treeMap = new TreeMap<>(ordering);
treeMap.putAll(mapOfKennelsAndDogs);
在我的代码中有以下 HashMap
,其中 key
是一个 Kennel 对象,value
是该 kennel 中的 Dog 对象列表。
填充 HashMap
后,我可以将其转换为 Treemap
并传入比较器吗?
Map<Kennel, List<Dog>> mapOfKennelsAndDogs;
//populate the map
//convert it to a treemap?
只需使用比较器创建树状图,然后添加所有条目。
Comparator<Kennel> ordering = ...;
TreeMap<Kennel, List<Dog>> treeMap = new TreeMap<>(ordering);
treeMap.putAll(mapOfKennelsAndDogs);