如何使用比较器将HashMap转换为TreeMap?

时间:2016-06-07 09:37:49

标签: java hashmap treemap

在我的代码中,我有以下HashMap,其中key是一个Kennel对象,value是该狗窝中Dog对象的列表。

当我填充HashMap时,我可以将其转换为Treemap并传入比较器吗?

Map<Kennel, List<Dog>> mapOfKennelsAndDogs;

//populate the map

//convert it to a treemap?

1 个答案:

答案 0 :(得分:2)

只需使用比较器创建树形图,然后添加所有条目。

Comparator<Kennel> ordering = ...;
TreeMap<Kennel, List<Dog>> treeMap = new TreeMap<>(ordering);
treeMap.putAll(mapOfKennelsAndDogs);
相关问题