Retrieve TreeMap size in Java

Java 8Object Oriented ProgrammingProgramming

Get the TreeMap size using the size() method.

First, create a TreeMap and add elements to it −

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");

Count the number of elements in the above TreeMap or get the size using the size() method as shown below −

m.size()

To get the size of TreeMap, the following is the code −

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");
      System.out.println("TreeMap Elements...\n"+m);
      System.out.println("\nSize of TreeMap: " + m.size());
   }
}

Output

TreeMap Elements...
{1=PHP, 2=jQuery, 3=JavaScript, 4=Ruby, 5=Java, 6=AngularJS, 7=ExpressJS}
Size of TreeMap: 7
raja
Published on 30-Jan-2019 08:03:46
Advertisements