Element Management Techniques
Adding Elements
TreeMap provides multiple methods to add elements efficiently:
public class ElementAdditionDemo {
public static void main(String[] args) {
TreeMap<String, Integer> inventory = new TreeMap<>();
// Basic put method
inventory.put("Laptop", 50);
// putIfAbsent - adds only if key doesn't exist
inventory.putIfAbsent("Smartphone", 100);
// Bulk insertion
Map<String, Integer> newItems = Map.of(
"Tablet", 75,
"Headphones", 200
);
inventory.putAll(newItems);
}
}
Retrieving Elements
Key Retrieval Techniques
Method |
Description |
Return Value |
get(key) |
Retrieves value |
Value or null |
getOrDefault(key, defaultValue) |
Safe retrieval |
Specified default if key not found |
firstKey() |
Gets smallest key |
First key |
lastKey() |
Gets largest key |
Last key |
Removing Elements
public class ElementRemovalDemo {
public static void main(String[] args) {
TreeMap<String, Integer> scores = new TreeMap<>();
scores.put("Alice", 95);
scores.put("Bob", 87);
// Remove specific entry
scores.remove("Alice");
// Conditional removal
scores.remove("Bob", 87);
}
}
Advanced Navigation Methods
graph LR
A[Navigation Methods] --> B[headMap]
A --> C[tailMap]
A --> D[subMap]
Range and Navigation Operations
public class NavigationDemo {
public static void main(String[] args) {
TreeMap<Integer, String> ages = new TreeMap<>();
ages.put(25, "Young");
ages.put(40, "Middle-aged");
ages.put(60, "Senior");
// Get subset of map
SortedMap<Integer, String> youngAges = ages.headMap(40);
SortedMap<Integer, String> olderAges = ages.tailMap(40);
}
}
Key Iteration Strategies
public class IterationDemo {
public static void main(String[] args) {
TreeMap<String, Double> prices = new TreeMap<>();
// Ascending order iteration
for (Map.Entry<String, Double> entry : prices.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
// Descending order iteration
NavigableSet<String> descendingKeys = prices.descendingKeySet();
}
}
- Use
containsKey()
for efficient existence checks
- Prefer
getOrDefault()
over manual null checks
- Choose appropriate initial capacity for large datasets