TreeMap

Obtain tail map from TreeMap example

This is an example of how to obtain a tail map from a TreeMap. The TreeMap API provides methods for this operation. Obtaining a tail map from a TreeMap implies that you should:

  • Create a new TreeMap.
  • Populate the map with elements, with put(K key, V value) API method of TreeMap.
  • Invoke tailMap(Object fromKey) API method of TreeMap. It returns a SortedMap, that is the portion of the map whose keys are greater than the specified fromKey. The SortedMap returned is backed by the original TreeMap, so any changes made to SortedMap will be reflected back to the original TreeMap.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;

import java.util.SortedMap;
import java.util.TreeMap;
 
public class TailMapTreeMap {
 
  public static void main(String[] args) {
 
    // Create a TreeMap and populate it with elements
    TreeMap treeMap = new TreeMap();
    treeMap.put("key_1","element_1");
    treeMap.put("key_3","element_3");
    treeMap.put("key_2","element_2");
    treeMap.put("key_4","element_4");
    treeMap.put("key_5","element_5");
 
    /*

SortedMap tailMap(Object fromKey) returns the portion of TreeMap whose keys are grater than fromKey.

The SortedMap returned is backed by the original TreeMap. So any changes made to SortedMap will 

be reflected back to original TreeMap.
    */
    SortedMap tailMap = treeMap.tailMap("key_3");
    System.out.println("tailMap Contains : " + tailMap);
  }
}

Output:

tailMap Contains : {key_3=element_3, key_4=element_4, key_5=element_5}

 
This was an example of how to obtain a tail map from a TreeMap in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button