Get Sub Map from TreeMap in Java

Java 8Object Oriented ProgrammingProgramming

To get Sub Map in Java, use the submap() method. It returns the elements in a range from the Map.

First, create a TreeMap and add elements −

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

Now, get the Sub Map between 4 and 6 −

m.subMap(4, 6)

The following is an example to get Sub Map from Tree Map in Java

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("Sub Map = " + m.subMap(4, 6));
   }
}

Output

TreeMap Elements...
{1=PHP, 2=jQuery, 3=JavaScript, 4=Ruby, 5=Java, 6=AngularJS, 7=ExpressJS}
Sub Map = {4=Ruby, 5=Java}
raja
Published on 11-Jan-2019 06:50:31
Advertisements