How to Get a Set of Keys from Java LinkedHashMap


Here this example aims to get a set of keys contained in LinkedHashMap by keySet method.

Source Code

package com.beginner.examples;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Set;

public class GetSetViewOfKeysFromLinkedHashMap {

	public static void main(String[] args) {
		
		//create LinkedHashMap.
		LinkedHashMap linkedHashMap = new LinkedHashMap();
		
		linkedHashMap.put("1","Alice");
		linkedHashMap.put("2","Bob");
		linkedHashMap.put("3","Jack");
		
		/*
		 * get Set of keys contained in LinkedHashMap using keySet() method of LinkedHashMap.
		 */
		Set set = linkedHashMap.keySet();
		Iterator iterator = set.iterator();
		System.out.println("LinkedHashMap Keys contains :");
		while(iterator.hasNext()) {
			System.out.println(iterator.next());
		}

	}

}

Output:

LinkedHashMap Keys contains :
1
2
3

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments