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