2

I am using TreeMap to sort the keys in the Map.

Map<Byte, List<TagEntity>> hashMap = list.stream().collect(Collectors.groupingBy(TagEntity::getTagType));

Map<Byte, List<TagEntity>> treeMap = new TreeMap<>(Comparator.reverseOrder());

But how to convert HashMap to TreeMap?

dai
  • 1,025
  • 2
  • 13
  • 33

3 Answers3

3

You can create the TreeMap directly by passing a map supplier to groupingBy:

Map<Byte, List<TagEntity>> treeMap = 
    list.stream()
        .collect(Collectors.groupingBy(TagEntity::getTagType,
                                      () -> new TreeMap<Byte, List<TagEntity>>(Comparator.reverseOrder()),
                                      Collectors.toList()));
Eran
  • 387,369
  • 54
  • 702
  • 768
2

This is how you can create hashmap to treemap:

HashMap<Integer, String> hashMap = new HashMap<Integer, String>();
TreeMap<Integer, String> treeMap = new TreeMap<Integer, String>();
treeMap.putAll(hashMap);

Refer here java-putting-hashmap-into-treemap

Abhijith S
  • 526
  • 5
  • 17
0

This should work:

TreeMap treeMap = new TreeMap<>(hashMap);

Or:

treeMap.putAll(hashMap);

Thiru
  • 2,541
  • 4
  • 25
  • 39