The emptyNavigableMap() method in Java returns an immutable NavigableMap that contains no key-value pairs. It is part of the java.util.Collections class and provides a convenient way to obtain an empty navigable map. This can be useful in scenarios where a method requires a navigable map but no mappings are available.
Table of Contents
- Introduction
emptyNavigableMap()Method Syntax- Examples
- Basic Usage of
emptyNavigableMap() - Using
emptyNavigableMap()in a Custom Method
- Basic Usage of
- Real-World Use Case
- Conclusion
Introduction
The Collections.emptyNavigableMap() method returns a statically typed, immutable navigable map that contains no elements. This method is useful when you need to return a navigable map from a method, but there are no key-value pairs to provide. By using emptyNavigableMap(), you can avoid returning null and prevent potential NullPointerException errors in your code.
A NavigableMap is an extension of the SortedMap interface that provides additional navigation methods, such as lowerKey(), floorKey(), ceilingKey(), and higherKey(). The map returned by emptyNavigableMap() is immutable, meaning it cannot be modified. Any attempts to add, remove, or change entries will result in an UnsupportedOperationException.
emptyNavigableMap() Method Syntax
The syntax for the emptyNavigableMap() method is as follows:
public static final <K, V> NavigableMap<K, V> emptyNavigableMap()
Parameters:
- This method does not take any parameters.
Returns:
- An immutable empty
NavigableMap.
Examples
Basic Usage of emptyNavigableMap()
The following example demonstrates how to use the emptyNavigableMap() method to obtain an immutable empty navigable map.
Example
import java.util.Collections;
import java.util.NavigableMap;
public class EmptyNavigableMapExample {
public static void main(String[] args) {
// Obtain an empty navigable map
NavigableMap<String, Integer> emptyNavigableMap = Collections.emptyNavigableMap();
// Check if the navigable map is empty
System.out.println("Is the navigable map empty? " + emptyNavigableMap.isEmpty());
// Attempt to access entries in the navigable map
System.out.println("Navigable map size: " + emptyNavigableMap.size());
// Attempt to modify the navigable map (will throw UnsupportedOperationException)
try {
emptyNavigableMap.put("Key", 1);
} catch (UnsupportedOperationException e) {
System.out.println("Error: Cannot add entries to an immutable navigable map");
}
}
}
Output:
Is the navigable map empty? true
Navigable map size: 0
Error: Cannot add entries to an immutable navigable map
Using emptyNavigableMap() in a Custom Method
You can use the emptyNavigableMap() method to return an empty navigable map from a custom method when there are no key-value pairs to provide.
Example
import java.util.Collections;
import java.util.NavigableMap;
import java.util.TreeMap;
public class CustomMethodExample {
public static void main(String[] args) {
// Get a non-empty navigable map of fruits and their quantities
NavigableMap<String, Integer> fruitQuantities = getFruitQuantities(true);
System.out.println("Fruit Quantities (non-empty): " + fruitQuantities);
// Get an empty navigable map of fruits and their quantities
fruitQuantities = getFruitQuantities(false);
System.out.println("Fruit Quantities (empty): " + fruitQuantities);
}
// Method to return a navigable map of fruits and their quantities based on a condition
public static NavigableMap<String, Integer> getFruitQuantities(boolean hasFruits) {
if (hasFruits) {
NavigableMap<String, Integer> fruits = new TreeMap<>();
fruits.put("Apple", 5);
fruits.put("Banana", 10);
return fruits;
} else {
return Collections.emptyNavigableMap();
}
}
}
Output:
Fruit Quantities (non-empty): {Apple=5, Banana=10}
Fruit Quantities (empty): {}
Explanation:
-
Non-Empty Navigable Map: When
hasFruitsistrue, thegetFruitQuantities()method returns a navigable map containing fruits and their quantities using aTreeMap. -
Empty Navigable Map: When
hasFruitsisfalse, the method returns an empty navigable map usingemptyNavigableMap(), demonstrating its utility in cases where no entries are needed.
Real-World Use Case
Providing Default Empty Navigable Maps in APIs
In API development, it is common to have methods that return navigable maps. Using emptyNavigableMap() can provide a safe default when there are no key-value pairs to return, avoiding null values and potential errors.
Example
Imagine a scenario where you have an API method that retrieves a navigable map of product IDs and their associated prices based on specific criteria. If no products meet the criteria, you can return an empty navigable map instead of null.
import java.util.Collections;
import java.util.NavigableMap;
import java.util.TreeMap;
class Product {
String name;
double price;
Product(String name, double price) {
this.name = name;
this.price = price;
}
@Override
public String toString() {
return name + " ($" + price + ")";
}
}
public class ProductService {
// Method to get a navigable map of product names and their prices based on a condition
public NavigableMap<String, Double> getProductPrices(boolean hasProducts) {
if (hasProducts) {
NavigableMap<String, Double> productPrices = new TreeMap<>();
productPrices.put("Laptop", 1500.00);
productPrices.put("Smartphone", 800.00);
return productPrices;
} else {
return Collections.emptyNavigableMap();
}
}
public static void main(String[] args) {
ProductService productService = new ProductService();
// Retrieve a non-empty navigable map of product prices
NavigableMap<String, Double> productPrices = productService.getProductPrices(true);
System.out.println("Product Prices (non-empty): " + productPrices);
// Retrieve an empty navigable map of product prices
productPrices = productService.getProductPrices(false);
System.out.println("Product Prices (empty): " + productPrices);
}
}
Output:
Product Prices (non-empty): {Laptop=1500.0, Smartphone=800.0}
Product Prices (empty): {}
Explanation:
-
Non-Empty Navigable Map: When
hasProductsistrue, thegetProductPrices()method returns a navigable map of product prices, demonstrating how maps can be populated with entries when available. -
Empty Navigable Map: When
hasProductsisfalse, thegetProductPrices()method returns an empty navigable map usingemptyNavigableMap(), ensuring that the method handles cases with no products correctly.
Conclusion
The Collections.emptyNavigableMap() method is a useful utility for obtaining an immutable empty navigable map in Java. By providing a typesafe, empty navigable map, it helps prevent NullPointerException errors and ensures that your code handles cases where no elements are present gracefully. This method is particularly valuable when implementing APIs or methods that require navigable maps but may not always have entries to return, enhancing the robustness and maintainability of your Java applications.