简体   繁体   中英

How to store multiple values in hashmap with respect to unique keys

Hi i have to validate the database values with the UI displayed values so I am using Watij as an automation tool. The problem arises when i have to store the database values into the hashmap. Suppose the database is having 3 fields Name, Email and Address. And after firing the query the fetched rows are 10. I am taking the field values as the Key in hashmap and the retrieved rows as the values.

I am unable to store the values in hashmap. When i used the hashmap the values got overridden and at last i always got the single values for the respective keys. I tried declaring the hashmap having two parameters as string and an string[] but i was unable to read the final values. Can anybody help as i am not a java expert. Thanks.

Where have you declared the string? You will have to declare it inside the loop(where you loop through your resultset). If you are not creating a new object inside the loop, the reference of the same string would be stored in all the values of the hashmap and you would get a single value in your hashmap. If the code was also mentioned here, it would be easy to pinpoint the exact problem.

Well in a map, the keys need to be unique, so if you keep add (email,blabla@hotmail.com) and it already had (email,nana@gmail.com) they you would just override the first one. If what you want is just a list of emails, adresses and names wouldn't it be better to make a class called person or something and add those to a list?

Like person(name,email,adress) then add that to a list.

when storing object in hashmap, you can use the hashcode of that object as key and then can save the object itself as the value, but make sure that you implement hasCode() and equals method properly, as u know, hashmap internally used hashcode() and 'equals` method for storing data.

Now when implementing hashcode or equals method, you can use any attribute (column of that row), which u think, that uniquely identify that row.

And moreover, performance wise this will be a better approach.

You can make a map like as HashMap<String, Data> where the first argument is the key (I suppose a String , you can use what you want) and Data is aa class that contains the data values for the key. Data may be:

public class Data {

    private String name;
    private String address;
    private String email;

    ...
}

You can add object to the map with map.put(key, new Data(...)) . A more simple way is use array, in a map like HashMap<String,String[]> , but is not very useful. The Java idea with DB query is to create object to encapsulate every record.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM