| by Arround The Web | No comments

Java Treemap Examples

Treemap is a useful data structure of Java that stores the data based on key-value pairs in sorted order. It implements a map from the Java Collections Framework (JCF). The entries of the treemap are sorted in the natural order and it contains unique values only. This means that the numeric values are sorted in ascending order and the string values are sorted in alphabetical order. It may contain null values but the key can’t be null in the treemap. A root node contains many sub-nodes. The NavigableMap interface is implemented by it. The “java.util” package is required to import the treemap class. The uses of the treemap class are explained in this tutorial using simple examples.

Prerequisites:

  1. Install the latest version of OpenJDK with JRE.
  2. Install any useful editor to write and execute the Java code. You can check this tutorial to install the Eclipse editor.

Benefits of Using Treemap

  • It can contain unlimited numbers of key-value pairs and performs better than the other data structures like Arrays, Linked List, HashMap, LinkedHashMap, etc.
  • It takes less memory space.
  • It is an efficient data structure for searching elements.

Methods to Add the Element to TreeMap

Three methods can be used to insert the data into a treemap. The purposes of these methods are mentioned in the following:

Method Purpose
put() It is used to insert a particular key-value pair to the map.
putAll()  It is used to insert all entries from a map to another map.
putIfAbsent() It is used to insert a particular key-value pair if the particular key is absent in the map.

Java Treemap Examples

Multiple treemap examples are shown in this part of the tutorial to sort the treemap values in different ways.

Example 1: Sort the Key Values Based on Numeric Values

Create a Java file with the following code that sorts the treemap values based on the numeric key values. A treemap of numeric key and numeric value is declared in this example. Next, 5 entries are inserted into the treemap using the put() method. The iterator object is declared to iterate the treemap values using a loop and print the keys and values in the output.

//Import necessary modules
import java.util.TreeMap;
import java.util.Set;
import java.util.Iterator;
import java.util.Map;

public class JavaTreeMap2 {

    public static void main(String[] args) {
       
        //Declare a treemap object  
        TreeMap<Integer, Integer> tmp =  new TreeMap<Integer, Integer>();

        //Add elements to the treemap
        tmp.put(78765, 800000);
        tmp.put(45574, 12000);
        tmp.put(98675, 340000);
        tmp.put(56234, 784000);
        tmp.put(74234, 650000);

        //Create objects to iterate the values of the Treemap
        Set<?> set = tmp.entrySet();
        Iterator<?> iterator = set.iterator();
       
        while(iterator.hasNext()) {
            @SuppressWarnings("rawtypes")
            Map.Entry n_entry = (Map.Entry)iterator.next();
            System.out.println("Customer ID:" + n_entry.getKey());
            System.out.println("Customer Balance:" + n_entry.getValue() + "\n");        
        }
    }
}

The following output appears after executing the previous script. The content of the treemap is printed based on the sorted key values:

Example 2: Sort the Key Values Based on String Values

Create a Java file with the following code that sorts the treemap values based on the string key values. A treemap of string key and numeric value is declared in this example. Next, 3 entries are inserted into the treemap using the put() method. The iterator object is declared to iterate the treemap values using a loop and print the keys and values in the output.

//Import necessary modules
import java.util.TreeMap;
import java.util.Set;
import java.util.Iterator;
import java.util.Map;

public class JavaTreeMap {

    public static void main(String[] args) {
       
        //Declare a treemap object  
        TreeMap<String, Integer> tmp =  new TreeMap<String, Integer>();

        //Add elements to the treemap
        tmp.put("Mark", 95);
        tmp.put("Janifer", 78);
        tmp.put("Ella", 83);

        //Create objects to iterate the values of the Treemap
        Set<?> set = tmp.entrySet();
        Iterator<?> iterator = set.iterator();
       
        while(iterator.hasNext()) {
            @SuppressWarnings("rawtypes")
            Map.Entry n_entry = (Map.Entry)iterator.next();
            System.out.println(n_entry.getKey() + " obtained " + n_entry.getValue() + " marks ");
        }
    }
}

The following output appears after executing the previous code. The content of the treemap is printed based on the sorted key values. Here, the values of the key are sorted based on alphabetic order:

Example 3: Sort the Key Values in Descending Order

The key values are sorted in ascending order by default in the treemap. Create a Java file with the following code that sorts the treemap values based on the numeric key values in descending order. A treemap of numeric key and string value is declared in this example. Next, 5 entries are inserted into the treemap using the put() method. The map object is created to sort the treemap values in descending order.

//Import necessary modules
import java.util.TreeMap;
import java.util.Collections;
import java.util.Map;

public class JavaTreeMap3 {

    public static void main(String[] args) {
       
        //Declare a treemap object  
        TreeMap<Integer, String> tmp =  new TreeMap<Integer, String>();

               //Add elements to the treemap
        tmp.put(345, "Pen");
        tmp.put(897, "Pencil");
        tmp.put(323, "NoteBook");
        tmp.put(545, "Color Pencil");
        tmp.put(654, "Drawing Book");

        //Create a new treemap object to sort keys in descending order
        Map<Integer, String> sortDesc = new TreeMap<>(Collections.reverseOrder());

        //Sort the map in descending order
        sortDesc.putAll(tmp);
       
        System.out.println("Key => Value");
        //Print the key-value pairs in descending order
        for(Map.Entry<Integer, String> entry : sortDesc.entrySet()) {    
                               System.out.println(entry.getKey() + "=>" +  entry.getValue());
                       }
    }
}

The following output appears after executing the previous code:

Example 4: Remove the Treemap Value

The remove() method is used to remove the element from the treemap based on the key value.

This method returns true if any entry is removed from the treemap. Create a Java file with the following code that removes an entry of the treemap that contains the key value of 323:

//Import necessary modules
import java.util.TreeMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class JavaTreeMap4 {

    public static void main(String[] args) {
       
        //Declare a treemap object  
          TreeMap<Integer, String> tmp =  new TreeMap<Integer, String>();

        //Add elements to the treemap
        tmp.put(345, "Pen");
        tmp.put(897, "Pencil");
        tmp.put(323, "NoteBook");
        tmp.put(545, "Color Pencil");
        tmp.put(654, "Drawing Book");
       
          //Remove key-value based on a key
          String value = tmp.remove(323);
          System.out.println("The removed value is " + value);

        //Create objects to iterate the values of the Treemap
        Set<?> set = tmp.entrySet();
        Iterator<?> iterator = set.iterator();
       
        System.out.println("Treemap entries after remove:");
       
        while(iterator.hasNext()) {
            @SuppressWarnings("rawtypes")
            Map.Entry n_entry = (Map.Entry)iterator.next();
            System.out.println(n_entry.getKey() + " => " + n_entry.getValue());
        }
    }
}

The following output appears after executing the previous code:

Conclusion

The methods of inserting, removing, and printing the elements of the treemap are shown in this tutorial using multiple examples that will help the Java users to learn how to use the Java treemap.

Share Button

Source: linuxhint.com

Leave a Reply