LinkedHashMap is a predefined class in Java that is similar to HashMap, contains a key and its respective value. Unlike HashMap, In LinkedHashMap insertion order is preserved. The task is to print all the Keys present in our LinkedHashMap in java. We have to iterate through each Key in our LinkedHashMap and print It.
Example :
Input : Key- 1 : Value-5
Key- 29 : Value-13
Key- 14 : Value-10
Key- 34 : Value-2
Key- 55 : Value-6
Output: 1, 29, 14, 34, 55
Method 1: Use for-each loop to iterate through LinkedHashMap. For each iteration, we print the respective key using getKey() method.
for(Map.Entry<Integer,Integer>ite : LHM.entrySet())
System.out.print(ite.getKey()+", ");
Example 1:
Java
import java.util.*;
import java.io.*;
class GFG {
public static void main(String[] args)
{
LinkedHashMap<Integer, Integer> LHM
= new LinkedHashMap<>();
LHM.put( 1 , 5 );
LHM.put( 29 , 13 );
LHM.put( 14 , 10 );
LHM.put( 34 , 2 );
LHM.put( 55 , 6 );
for (Map.Entry<Integer, Integer> ite :
LHM.entrySet())
System.out.print(ite.getKey() + ", " );
}
}
|
Output
1, 29, 14, 34, 55,
Example 2:
Java
import java.util.*;
import java.io.*;
class GFG {
public static void main(String[] args)
{
LinkedHashMap<String, String> LHM
= new LinkedHashMap<>();
LHM.put( "Geeks" , "Geeks" );
LHM.put( "for" , "for" );
LHM.put( "Geeks" , "Geeks" );
for (Map.Entry<String, String> ite : LHM.entrySet())
System.out.print(ite.getKey() + ", " );
}
}
|
Method 2: (Using keySet() method)
Syntax:
hash_map.keySet()
Parameters: The method does not take any parameters.
Return Value: The method returns a set having the keys of the hash map.
Java
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
LinkedHashMap<String, String> lhm
= new LinkedHashMap<String, String>();
lhm.put( "One" , "Geeks" );
lhm.put( "Two" , "For" );
lhm.put( "Three" , "Geeks" );
Set<String> allKeys = lhm.keySet();
System.out.println(allKeys);
}
}
|
Feeling lost in the vast world of Backend Development? It's time for a change! Join our
Java Backend Development - Live Course and embark on an exciting journey to master backend development efficiently and on schedule.
What We Offer:
- Comprehensive Course
- Expert Guidance for Efficient Learning
- Hands-on Experience with Real-world Projects
- Proven Track Record with 100,000+ Successful Geeks
Last Updated :
17 Dec, 2020
Like Article
Save Article