Inserting Elements
Basic Insertion Methods
TreeMap provides several methods for inserting elements:
put() Method
The primary method for inserting key-value pairs:
TreeMap<String, Integer> treeMap = new TreeMap<>();
treeMap.put("Java", 100); // Inserts a key-value pair
putAll() Method
Inserts multiple entries from another map:
Map<String, Integer> sourceMap = new HashMap<>();
sourceMap.put("Python", 95);
sourceMap.put("JavaScript", 90);
TreeMap<String, Integer> targetMap = new TreeMap<>();
targetMap.putAll(sourceMap);
Insertion Behavior
graph TD
A[Insertion Process] --> B{Key Already Exists?}
B -->|Yes| C[Replace Existing Value]
B -->|No| D[Create New Entry]
C --> E[Return Old Value]
D --> F[Maintain Sorted Order]
Handling Duplicate Keys
Scenario |
Behavior |
Return Value |
New Key |
Insert Entry |
null |
Existing Key |
Replace Value |
Previous Value |
Advanced Insertion Techniques
Using putIfAbsent()
Inserts only if the key doesn't exist:
TreeMap<String, Integer> scores = new TreeMap<>();
scores.putIfAbsent("Alice", 95); // Inserts if "Alice" not present
Conditional Insertion
TreeMap<String, Integer> studentScores = new TreeMap<>();
studentScores.compute("Bob", (key, oldValue) ->
(oldValue == null) ? 90 : oldValue + 5
);
- Insertion time complexity: O(log n)
- Maintains sorted order during insertion
- Slightly slower compared to HashMap
Complete Example
public class TreeMapInsertionDemo {
public static void main(String[] args) {
TreeMap<String, Integer> programmingScores = new TreeMap<>();
// Basic insertion
programmingScores.put("Java", 95);
programmingScores.put("Python", 90);
// Conditional insertion
programmingScores.merge("Java", 5, Integer::sum);
// Print results
programmingScores.forEach((language, score) ->
System.out.println(language + ": " + score)
);
}
}
By mastering these insertion techniques, you'll effectively manage sorted collections in your Java applications with LabEx.