Get Head Map from TreeMap in Java


Use the headMap() method in Java to get ahead map. It returns a view of the portion of this map whose keys are less than or equal to.

Let’s say you need to get the portion of the map above the set map (and not inclusive of it). For that, use the headMap() method like this −

m.headMap(4)

If you want the value 4 to be included as well, then set it as true −

m.headMap(4, true)

The following is an example to get Head Map from Java 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");
      System.out.println("TreeMap Elements...
"+m);       System.out.println("
Head Map has = "+m.headMap(4));    } }

Output

TreeMap Elements...
{1=PHP, 2=jQuery, 3=JavaScript, 4=Ruby, 5=Java, 6=AngularJS, 7=ExpressJS}
Head Map has = {1=PHP, 2=jQuery, 3=JavaScript}

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jul-2019

135 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements