13.05. TreeMap

TreeMap

  • Eclipse: Oxygen
  • Java: 1.8

In Java TreeMap is the kind of map data, but the natural order of the keys is preserved. Therefore TreeMap implements the map interface and navigable map along with the abstract class.

In the following program, we are making use of HashMap based on lectures. The key symbolizes the serial number of the lecture and the value pair gives us the title of the lecture. By using foreach loop we will display the value.

Here we are demonstrating that TreeMap class implements a Comparable interface similar to the HashMap class but the main difference between them is that HashMap is an unordered collection while TreeMap is sorted in the ascending order of its keys.

Output

Key: Code [sectionNo=S02, lectureNo=L03] Value: Network programming

Key: Code [sectionNo=S01, lectureNo=L03] Value: Expressions

Key: Code [sectionNo=S01, lectureNo=L05] Value: Methods

Key: Code [sectionNo=S01, lectureNo=L03] Value: Generics

Key: Code [sectionNo=S01, lectureNo=L01] Value: Files under Java

Key: Code [sectionNo=S01, lectureNo=L07] Value: OOPS

In the following program, we have inserted the data in random order however when we displayed the TreeMap content we got the sorted result in the ascending order of keys.

Output

Key: Code [sectionNo=S01, lectureNo=L01] Value: Files under Java

Key: Code [sectionNo=S01, lectureNo=L03] Value: Expressions

Key: Code [sectionNo=S01, lectureNo=L05] Value: Methods

Key: Code [sectionNo=S01, lectureNo=L07] Value: OOPS

Key: Code [sectionNo=S02, lectureNo=L03] Value: Network programming

Contributed by Poonam Tomar

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments