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));
}
}
Printing All Keys and Values From the HashMapkeys. forEach(key -> System. out. println(key));
How To Find Duplicate Elements In Array In Java Using HashMap? In this method, We use HashMap to find duplicates in array in java. We store the elements of input array as keys of the HashMap and their occurrences as values of the HashMap. If the value of any key is more than one (>1) then that key is duplicate element.
You could do a check using the Map's containsKey() method to see if the key is already present in your Map. A hash map can only store one value for each key. So if you do add another "David" with value 555 it will overwrite the original value.
HashMap stores key, value pairs and it does not allow duplicate keys. If the key is duplicate then the old key is replaced with the new value.
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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With