Create a TreepMap in Java and add elements

Java 8Object Oriented ProgrammingProgramming

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
raja
Updated on 30-Jul-2019 22:30:24

Advertisements