riven

Riven

Riven

what is Treemap in java with example

in Java, a TreeMap is part of the Java Collections Framework and provides a navigable map implementation based on a red-black tree. It stores key-value pairs in a sorted order, meaning that the keys are sorted according to their natural ordering or by a specified comparator. This makes TreeMap particularly useful for applications that require sorted data.

This guide will delve into the characteristics, operations, and practical examples of using TreeMap in Java, along with a comparison to other map implementations.

What is TreeMap?

A TreeMap is a map implementation that maintains its entries in ascending key order. It implements the NavigableMap interface, which means it provides methods to navigate through the keys, retrieve entries, and perform range queries.

Key Characteristics of TreeMap

  1. Sorted Order: The entries are sorted based on the natural ordering of the keys or by a custom comparator.
  2. Navigable: It provides methods to navigate through the keys and access sub-maps.
  3. Non-Null Keys: TreeMap does not allow null keys, though it permits null values.
  4. Performance: The time complexity for basic operations like get(), put(), and remove() is O(log n), due to the underlying red-black tree structure.
  5. Synchronized: It is not synchronized; thus, if multiple threads access a TreeMap, external synchronization is necessary.

Creating a TreeMap

To create a TreeMap, you need to import the necessary classes from the java.util package and instantiate a TreeMap object.

Example: Creating a TreeMap

				
					import java.util.TreeMap;
import java.util.Map;

public class TreeMapExample {
    public static void main(String[] args) {
        // Creating a TreeMap
        Map<String, Integer> ageMap = new TreeMap<>();

        // Adding key-value pairs
        ageMap.put("Alice", 30);
        ageMap.put("Bob", 25);
        ageMap.put("Charlie", 35);
        ageMap.put("Diana", 28); // Adding another entry

        // Displaying the TreeMap
        System.out.println("Age Map: " + ageMap);
    }
}
Output:


Age Map: {Alice=30, Bob=25, Charlie=35, Diana=28}
				
			

Common Operations on TreeMap

1. Adding Key-Value Pairs

You can add key-value pairs to a TreeMap using the put() method. If the key already exists, the existing value will be replaced.

Example: Adding Key-Value Pairs

				
					ageMap.put("Eve", 28); // Adding a new entry
ageMap.put("Alice", 31); // Updating Alice's age
System.out.println("Updated Age Map: " + ageMap);
				
			

2. Removing Key-Value Pairs

You can remove a key-value pair from a TreeMap using the remove() method. If the key does not exist, the method does nothing.

Example: Removing Key-Value Pairs

				
					ageMap.remove("Bob"); // Removing Bob's entry
System.out.println("After removing Bob: " + ageMap);
				
			

3. Accessing Values

You can retrieve the value associated with a specific key using the get() method. If the key does not exist, the method returns null.

Example: Accessing Values

				
					Integer aliceAge = ageMap.get("Alice");
System.out.println("Alice's age: " + aliceAge);
				
			

4. Checking for Keys and Values

You can check if a TreeMap contains a specific key or value using the containsKey() and containsValue() methods.

Example: Checking for Keys and Values

				
					boolean hasCharlie = ageMap.containsKey("Charlie");
boolean hasAge30 = ageMap.containsValue(30);
System.out.println("Contains Charlie? " + hasCharlie);
System.out.println("Contains age 30? " + hasAge30);
				
			

5. Getting the Size of the TreeMap

You can find out the number of key-value pairs in a TreeMap using the size() method.

Example: Getting the Size

				
					System.out.println("Size of the map: " + ageMap.size());
				
			

6. Clearing the TreeMap

To remove all key-value pairs from a TreeMap, you can use the clear() method.

Example: Clearing the TreeMap

				
					ageMap.clear();
System.out.println("After clearing the map: " + ageMap);
				
			

Iterating Over a TreeMap

You can iterate over the entries of a TreeMap using different methods, such as the enhanced for loop, entry set, or key set.

Example: Iterating Using Entry Set

				
					for (Map.Entry<String, Integer> entry : ageMap.entrySet()) {
    System.out.println(entry.getKey() + ": " + entry.getValue());
}
				
			

Example: Iterating Using Key Set

				
					for (String key : ageMap.keySet()) {
    System.out.println(key + ": " + ageMap.get(key));
}
				
			

Example: Using forEach Method

Java 8 introduced the forEach method for maps

				
					ageMap.forEach((key, value) -> {
    System.out.println(key + ": " + value);
});
				
			

Performance Considerations

Time Complexity

The average time complexity for basic operations in a TreeMap is:

  • Add (put): O(log n)
  • Remove: O(log n)
  • Contains (containsKey): O(log n)

This performance is due to the red-black tree structure that maintains the sorted order of the keys.

Memory Usage

TreeMap uses a binary search tree structure, which generally requires more memory compared to HashMap due to additional pointers for tree nodes.

Use Cases for TreeMap

  1. Sorted Data Storage: Use TreeMap when you need to maintain a sorted order of keys, such as in applications that require sorted lists.
  2. Range Queries: It is useful for range queries, where you need to retrieve a subset of keys that fall within a specific range.
  3. Navigable Operations: TreeMap allows operations like finding the greatest key less than or equal to a given key, making it ideal for navigation-related applications.

Advanced Operations with TreeMap

SubMaps

TreeMap provides methods to retrieve sub-maps based on specified ranges. The subMap(), headMap(), and tailMap() methods allow you to create views of a portion of the map.

  • subMap(fromKey, toKey): Returns a view of the portion of this map whose keys range from fromKey, inclusive, to toKey, exclusive.
  • headMap(toKey): Returns a view of the portion of this map whose keys are strictly less than toKey.
  • tailMap(fromKey): Returns a view of the portion of this map whose keys are greater than or equal to fromKey.

Example: Using SubMaps

				
					Map<String, Integer> subMap = ageMap.subMap("Alice", "Diana");
System.out.println("SubMap: " + subMap);
				
			

Navigable Operations

TreeMap offers navigable operations that allow you to retrieve the closest matches for a given key.

  • firstKey(): Returns the first (lowest) key in this map.
  • lastKey(): Returns the last (highest) key in this map.
  • higherKey(key): Returns the least key strictly greater than the given key, or null if there is no such key.
  • lowerKey(key): Returns the greatest key strictly less than the given key, or null if there is no such key.

Example: Using Navigable Operations

				
					String firstKey = ageMap.firstKey();
String lastKey = ageMap.lastKey();
String higherKey = ageMap.higherKey("Bob");
String lowerKey = ageMap.lowerKey("Diana");

System.out.println("First Key: " + firstKey);
System.out.println("Last Key: " + lastKey);
System.out.println("Higher Key than Bob: " + higherKey);
System.out.println("Lower Key than Diana: " + lowerKey);
				
			

Custom Comparator

You can create a TreeMap with a custom comparator to define a specific order for the keys. This is useful when you need to sort keys based on specific criteria.

Example: Creating a TreeMap with a Custom Comparator

				
					import java.util.Comparator;

public class CustomComparatorExample {
    public static void main(String[] args) {
        TreeMap<String, Integer> customMap = new TreeMap<>(Comparator.reverseOrder());

        customMap.put("Alice", 30);
        customMap.put("Bob", 25);
        customMap.put("Charlie", 35);

        System.out.println("Custom Sorted TreeMap: " + customMap);
    }
}
Output:


Custom Sorted TreeMap: {Charlie=35, Alice=30, Bob=25}
				
			

Real-World Application Example: Employee Management System

Let’s create a simple console application to manage employee records using a TreeMap. This application will allow users to add employees, view all employees sorted by their names, and update specific employee details.

EmployeeManagement Class

				
					import java.util.TreeMap;
import java.util.Map;
import java.util.Scanner;

public class EmployeeManagement {
    private Map<String, Integer> employeeMap;

    public EmployeeManagement() {
        employeeMap = new TreeMap<>();
    }

    public void addEmployee(String name, int age) {
        employeeMap.put(name, age);
        System.out.println("Added employee: " + name);
    }

    public void viewEmployees() {
        System.out.println("Employee Records:");
        employeeMap.forEach((name, age) -> {
            System.out.println(name + ": " + age);
        });
    }

    public void updateEmployee(String name, int age) {
        if (employeeMap.containsKey(name)) {
            employeeMap.put(name, age);
            System.out.println("Updated employee: " + name);
        } else {
            System.out.println("Employee not found: " + name);
        }
    }

    public static void main(String[] args) {
        EmployeeManagement employeeManager = new EmployeeManagement();
        Scanner scanner = new Scanner(System.in);
        String command;

        System.out.println("Employee Management System");
        System.out.println("Commands: add [name] [age], view, update [name] [age], exit");

        while (true) {
            System.out.print("Enter command: ");
            command = scanner.nextLine();
            String[] parts = command.split(" ");
            switch (parts[0]) {
                case "add":
                    if (parts.length == 3) {
                        String name = parts[1];
                        int age = Integer.parseInt(parts[2]);
                        employeeManager.addEmployee(name, age);
                    } else {
                        System.out.println("Invalid command format. Use: add [name] [age]");
                    }
                    break;
                case "view":
                    employeeManager.viewEmployees();
                    break;
                case "update":
                    if (parts.length == 3) {
                        String name = parts[1];
                        int age = Integer.parseInt(parts[2]);
                        employeeManager.updateEmployee(name, age);
                    } else {
                        System.out.println("Invalid command format. Use: update [name] [age]");
                    }
                    break;
                case "exit":
                    System.out.println("Exiting Employee Management System.");
                    scanner.close();
                    return;
                default:
                    System.out.println("Unknown command.");
            }
        }
    }
}
				
			

Explanation of the Employee Management System

  1. EmployeeManagement Class: This class maintains a TreeMap of employee names and their corresponding ages, providing methods to add employees, view all employees, and update specific employee details.
  2. User Interaction: The main method provides a command-line interface for users to manage employee records.
  3. Commands:
    • add [name] [age]: Adds a new employee with the specified age.
    • view: Displays all employee records sorted by names.
    • update [name] [age]: Updates the age of the specified employee.
    • exit: Exits the application.

related post

Functional interface in java
What is a Functional Interface in java 8? A functional interface in Java is an interface that contains...
Swing in java
Swing in java with example Java Swing is a part of Java Foundation Classes (JFC) that provides a rich...
Result set in java
Resultset in java with example In Java Database Connectivity (JDBC), the ResultSet interface represents...
Java method overriding
Java method overriding Method overriding is a fundamental concept in object-oriented programming (OOP)...
Filereader in java with example
Filereader in java with example Java’s FileReader class is a fundamental part of Java’s file handling...
Linkedlist in java with example
LinkedList in java with example In Java, the LinkedList class is part of the Java Collections Framework...
Java instanceof
Java instanceof In Java instanceof operator is a fundamental part of the language that allows you to...
Single inheritance in java
Single inheritance in java Inheritance is one of the core concepts of object-oriented programming (OOP)....
Multiple inheritance in java
Multiple inheritance in java Multiple inheritance is a feature in object-oriented programming where a...
Networking in java
Networking in java with example Networking is a crucial part of modern software development, enabling...