How do I print out all keys in hashmap?
41,949
Here we go:
System.out.println(phoneBook.keySet());
This will printout the set of keys in your Map using Set.toString() method. for example :
["a","b"]
Comments
-
Gurkang over 3 years
I'm trying to learn how hashmaps work and I've been fiddling with a small phonebook program.
But I'm stumped at what to do when I want to print out all the keys.
here's my code:
import java.util.HashMap; import java.util.*; public class MapTester { private HashMap<String, String> phoneBook; public MapTester(){ phoneBook = new HashMap<String, String>(); } public void enterNumber(String name, String number){ phoneBook.put(name, number); } public void printAll(){ //This is where I want to print all. I've been trying with iterator and foreach, but I can't get em to work } public void lookUpNumber(String name){ System.out.println(phoneBook.get(name)); } }
-
Sotirios Delimanolis over 9 yearsHave you read the javadoc?
-
azurefrog over 9 years
-
StackFlowed over 9 yearsphoneBook.keySet(); --> return a set of keys !
-
-
Gurkang over 9 yearsThank you, I didn't know that.
-
jjlema over 9 yearsIf the answer helped you, please mark it as accepted, thank you.