Java – HashMap places duplicate values unnecessarily
I have the following code. I want to insert the result into the database, but now I just want to print out the key with value
Before this code, use the key to set up HashMap, which can work normally
The following code loops through the tableview and gets the item from the column. If the item is equal to the key in the hash map, it puts the dogsid as the value into the HashMap
// loop through tableView items for (Dog item : BookDogTableView.getItems()) { // cell data is not null if ((BookDogSelectRunCol.getCellData(item) != null)) { // loop through map for (Integer key : hashMap.keySet()) { // if chosen run ID equals key if (BookDogSelectRunCol.getCellData(item)) { // put dog in map BookingInformation.hashMap.put(key,item.getDogID()); } } } for (Integer keyprint : hashMap.keySet()) { if (hashMap.get(keyprint) != 0) { System.out.println("RUn ID : " + keyprint + " DogID : " + hashMap.get(keyprint)); } } }
However, this will print to the screen using the repeat key
Is there any way to remove duplicate key values from the map or change the current code to avoid duplicate key value pairs
Solution
You cannot have duplicate keys in a HashMap
It turns out that you print in the for loop Display simplified code of the problem:
for (Dog item : BookDogTableView.getItems()) { // cell data is not null ... for (Integer keyprint : hashMap.keySet()) { if (hashMap.get(keyprint) != 0) { System.out.println("RUn ID : " + keyprint + " DogID : " + hashMap.get(keyprint)); } } } //close of outer for loop
The solution is to move the print loop out of the external for loop