Accessing Key-Value Pairs in a TreeMap
When working with a TreeMap
, you can access the key-value pairs in various ways. Here are some common methods:
Accessing Values by Key
You can use the get()
method to retrieve the value associated with a specific key in the TreeMap
.
TreeMap<String, Integer> treeMap = new TreeMap<>();
treeMap.put("apple", 3);
treeMap.put("banana", 2);
treeMap.put("cherry", 5);
int value = treeMap.get("banana"); // Returns 2
If the key doesn't exist in the TreeMap
, the get()
method will return null
.
Checking if a Key Exists
You can use the containsKey()
method to check if a specific key exists in the TreeMap
.
TreeMap<String, Integer> treeMap = new TreeMap<>();
treeMap.put("apple", 3);
treeMap.put("banana", 2);
treeMap.put("cherry", 5);
boolean containsKey = treeMap.containsKey("banana"); // Returns true
boolean doesNotContainKey = treeMap.containsKey("orange"); // Returns false
Accessing the First and Last Keys
You can use the firstKey()
and lastKey()
methods to retrieve the first and last keys in the TreeMap
, respectively.
TreeMap<String, Integer> treeMap = new TreeMap<>();
treeMap.put("apple", 3);
treeMap.put("banana", 2);
treeMap.put("cherry", 5);
String firstKey = treeMap.firstKey(); // Returns "apple"
String lastKey = treeMap.lastKey(); // Returns "cherry"
Accessing a Submap
You can use the subMap()
method to create a new TreeMap
that contains a subset of the key-value pairs from the original TreeMap
.
TreeMap<String, Integer> treeMap = new TreeMap<>();
treeMap.put("apple", 3);
treeMap.put("banana", 2);
treeMap.put("cherry", 5);
treeMap.put("date", 4);
treeMap.put("elderberry", 1);
TreeMap<String, Integer> subMap = treeMap.subMap("banana", true, "elderberry", false);
// subMap contains {"banana", 2}, {"cherry", 5}, {"date", 4}
By understanding these methods for accessing key-value pairs in a TreeMap
, you can effectively work with this data structure in your Java applications.