Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HashMap putting duplicate values unnecessarily

Tags:

java

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

The HashMap is set with keys prior to this code, which works fine.

The following code loops through a tableView, gets items from a column, if the item equals the key in the hash map then it puts the dogsID as a 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 prints to screen with duplicate keys.

Is there a way to either remove duplicate key-values from a map or to alter the current code to avoid duplicate key-value pairs

like image 695
NeiW Avatar asked Nov 18 '25 18:11

NeiW


1 Answers

There cannot be duplicate keys in a HashMap.

It turns out you are printing inside the for loop. Simplified code showing 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

Solution is just to move the printing for loop out of the outer for loop.

like image 80
weston Avatar answered Nov 20 '25 09:11

weston



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!