Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I print out all keys in hashmap? [duplicate]

Tags:

java

hashmap

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));
}
}
like image 942
Gurkang Avatar asked Nov 10 '14 15:11

Gurkang


People also ask

How print all keys in HashMap?

Printing All Keys and Values From the HashMapkeys. forEach(key -> System. out. println(key));

How do I find duplicates in a HashMap?

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.

How do I find duplicate keys on a map?

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.

What happens when HashMap duplicate keys?

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.


1 Answers

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"]
like image 167
nafas Avatar answered Oct 12 '22 12:10

nafas