Table of Contents
1. Using keySet()
HashMap<String, Integer> map = new HashMap<>();
map.put("Java", 1995);
map.put("Python", 1991);
Set<String> keys = map.keySet();
for (String key : keys) {
System.out.println(key);
}
2. Using entrySet()
HashMap<String, Integer> map = new HashMap<>();
map.put("JavaScript", 1995);
map.put("C++", 1979);
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey());
}
3. Using getKeys() (Java 10+)
HashMap<String, Integer> map = new HashMap<>();
map.put("Ruby", 1995);
map.put("Go", 2009);
Set<String> keys = map.keySet();
keys.forEach(System.out::println);
4. Using Stream API
HashMap<String, Integer> map = new HashMap<>();
map.put("Python", 1991);
map.put("Java", 1995);
map.keySet().stream().forEach(System.out::println);
5. Using Iterator
HashMap<String, Integer> map = new HashMap<>();
map.put("C++", 1979);
map.put("JavaScript", 1995);
Iterator<String> iterator = map.keySet().iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!