Retrieving TreeMap elements
We know that TreeMap is a key-value pair based data structure.
Sometimes, We need to retrieve all the keys of TreeMap
Sometimes, We need to retrieve value for the specified key from the TreeMap
Sometimes we need to retrieve all the values from a TreeMap
Let’s see how we can achieve all these retrievals
Case 1
Retrieve all the keys from TreeMap
We can use keyset() method of TreeMap to get all the keys in that Map.
Example
- import java.util.*;
- public class TreeMapRetrieveKeysExample {
- public static void main(String args[]) {
- TreeMap<Integer,String> tm = new TreeMap<>();
- tm.put(3, “Three”);
- tm.put(1, “One”);
- tm.put(2, “Two”);
- Set<Integer> keys = tm.keySet();
- System.out.println(“All the keys of TreeMap....”);
- System.out.println(keys);
- }
- }
import java.util.*; public class TreeMapRetrieveKeysExample { public static void main(String args[]) { TreeMap<Integer,String> tm = new TreeMap<>(); tm.put(3, “Three”); tm.put(1, “One”); tm.put(2, “Two”); Set<Integer> keys = tm.keySet(); System.out.println(“All the keys of TreeMap....”); System.out.println(keys); } }
Case 2
Retrieve all the values from TreeMap
We can use values() method to retrieve all the values from the TreeMap
Example
- import java.util.*;
- public class TreeMapRetrieveAllValuesExample {
- public static void main(String args[]) {
- TreeMap<Integer,String> tm = new TreeMap<>();
- tm.put(3, “Three”);
- tm.put(1, “One”);
- tm.put(2, “Two”);
- Collection values = tm.values();
- System.out.println(“All the values of TreeMap....”);
- System.out.println(values);
- }
- }
import java.util.*; public class TreeMapRetrieveAllValuesExample { public static void main(String args[]) { TreeMap<Integer,String> tm = new TreeMap<>(); tm.put(3, “Three”); tm.put(1, “One”); tm.put(2, “Two”); Collection values = tm.values(); System.out.println(“All the values of TreeMap....”); System.out.println(values); } }
Case 3
Retrieve value for the specified key from TreeMap
We can use get() method by passing a specific key to retrieve value for a specific key from the TreeMap using .
Example
- import java.util.*;
- public class TreeMapRetrieveValueForKeyExample {
- public static void main(String args[]) {
- TreeMap<Integer,String> tm = new TreeMap<>();
- tm.put(3, “Three”);
- tm.put(1, “One”);
- tm.put(2, “Two”);
- String value = tm.get(1);
- System.out.println(“Value for key 1….”);
- System.out.println(value);
- }
- }
import java.util.*; public class TreeMapRetrieveValueForKeyExample { public static void main(String args[]) { TreeMap<Integer,String> tm = new TreeMap<>(); tm.put(3, “Three”); tm.put(1, “One”); tm.put(2, “Two”); String value = tm.get(1); System.out.println(“Value for key 1….”); System.out.println(value); } }