Create a TreepMap in Java and add elements


Let us create TreeMap in Java. It stores unique elements in ascending order −

TreeMap<Integer,String> m = new TreeMap<Integer,String>();

Now let us add some elements −

m.put(1,"PHP");
m.put(2,"jQuery");
m.put(3,"JavaScript");
m.put(4,"Ruby");
m.put(5,"Java");
m.put(6,"AngularJS");
m.put(7,"ExpressJS");

The following is an example to create a TreeMap −

Example

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      TreeMap<Integer,String> m = new TreeMap<Integer,String>();
      m.put(1,"PHP");
      m.put(2,"jQuery");
      m.put(3,"JavaScript");
      m.put(4,"Ruby");
      m.put(5,"Java");
      m.put(6,"AngularJS");
      m.put(7,"ExpressJS");
      for(Map.Entry e:m.entrySet()){
         System.out.println(e.getKey()+" "+e.getValue());
      }
   }
}

Output

1 PHP
2 jQuery
3 JavaScript
4 Ruby
5 Java
6 AngularJS
7 ExpressJS

Updated on: 30-Jul-2019

28 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements