Get Tail Map from TreeMap in Java

Java 8Object Oriented ProgrammingProgramming

To get Tail Map from TreeMap, use the tailMap() method. It gets a part or view of the map whose keys are greater than equal to the key set as a parameter.

Let us first create a TreeMap −

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

Now, we will 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");

Get the Tail Map −

m.tailMap(4)

The following is an example to get Tail Map from TreeMap 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("Tail Map has: " + m.tailMap(4));
   }
}

Output

TreeMap Elements...
{1=PHP, 2=jQuery, 3=JavaScript, 4=Ruby, 5=Java, 6=AngularJS, 7=ExpressJS}
Tail Map has: {4=Ruby, 5=Java, 6=AngularJS, 7=ExpressJS}
raja
Published on 30-Jan-2019 06:52:54
Advertisements