trevor01010010 trevor01010010 - 1 year ago 61
Java Question

How would I print out the Keys and Values in this hashmap?

public class myclass
public static void main(String[] args){
Scanner scan = new Scanner(;
int array1[] = new int[4];
System.out.println("Enter some integers");
for(int i = 0; i <array1.length; i++){
array1[i] = scan.nextInt();
HashMap<String, Integer> map = new HashMap<>();
map.put("IdOne", array1[0]);
map.put("IdOne", array1[1]);
map.put("IdOne", array1[2]);

I want to be able to print the values that I entered into the array along with a key from the Hashmap.
Example output:

Enter some integers




IdOne 2

IdOne 3

IdOne 5

Answer Source

First, get the entries


then loop over them

for (Map.Entry entry : someMap.entries()) {
    // do something

then print out the key and the value

for (Map.Entry entry : someMap.entries()) {
    System.out.println("key: %s, value: %s\n", entry.getKey(), entry.getValue();