Search code examples
javahashmaptreemap

How to convert a HashMap to a TreeMap using a comparator?


In my code I have the following HashMap, where the key is a Kennel object and the value is a list of Dog objects in that kennel.

When I have populated my HashMap, can I then convert it to a Treemap and pass in a comparator?

Map<Kennel, List<Dog>> mapOfKennelsAndDogs;

//populate the map

//convert it to a treemap?

Solution

  • Just create the treemap with the comparator, and then add all the entries.

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