trevor01010010 trevor01010010 - 2 months ago 6
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(System.in);
int array1[] = new int[4];
System.out.println("Enter some integers");
for(int i = 0; i <array1.length; i++){
array1[i] = scan.nextInt();
}
Arrays.sort(array1);
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

3

5

2

IdOne 2

IdOne 3

IdOne 5

Answer

First, get the entries

someMap.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();
}
Comments