020-003-011

Sorted Map with TreeMap

Hard

Problem Description

Sorted Map with TreeMap

In this problem: You will create a map with automatically sorted keys using TreeMap, and also perform reverse sorting with a custom Comparator.

Learning Objective: Understand TreeMap's automatic sorting and custom sorting with Comparator

Overview

TreeMap uses a red-black tree internally and automatically sorts keys in natural order (or by a specified Comparator). Unlike HashMap, iteration order is guaranteed.

Specifications

  • Create a natural-order TreeMap<String, Integer>, add "cherry"=3, "apple"=5, "banana"=2
  • Output all entries as "{key}={value}" (keys in alphabetical order)
  • Create a reverse-order TreeMap<String, Integer> with Comparator.reverseOrder(), add same data
  • Output all entries in reverse order

Output Format

Natural order:
apple=5
banana=2
cherry=3
Reverse order:
cherry=3
banana=2
apple=5

Ready to Try Running Code?

Log in to access the code editor and execute your solutions for this problem.

Don't have an account?

Sign Up