HashMap unnecessarily duplicates values

I have the following code, I want to insert the results into the database, but for now I just want to print the keys with their values.

The HashMap is installed with keys before this code, which works great.

The following code goes through the tableView, gets the items from the column, if the item is equal to the key in the hashmap, then it puts the dogsID in the hashmap value.

  // 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 prints to the screen with duplicate keys.

Is there a way to remove duplicate key values ​​from the map, or change the current code to avoid duplicate key-value pairs.

+3


source to share


1 answer


Can't duplicate keys in HashMap

.

It turns out you are printing inside a loop for

. Simplified code showing 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 only to move the print path for

out of the outer loop for

.

+7


source







All Articles