In Step 6, we have again displayed all the entriesĪdding Entry with Duplicate Value in HashMap.In Step 5, we have added an entry with duplicate key.In Step 4 we have displayed entries, with getkey() and getvalue() methods that are discussed above.In Step 3, we have used for each loop to retrieve the values from the HashMap object.In Step 1, we have created an object of HashMap collection.("Entries after adding element with Duplicate Key") Įntries after adding element with Duplicate KeyĬonclusion: From output it is clear that HashMap does not allow Entry with duplicate key, it overlaps old value with new one, as shown in the output. Step 5: Adding element with duplicate key Step 1: Defining object of HashMap Class In this program we have created object of HashMap Class and added key value pairs, one with duplicate key, as shown in the following program import java.util.* HashMap does not allow Entry with duplicate key, it overlaps old value with new one. out.println(map.getKey()+” “+map.getValue()) įirst is getKey(), which as name suggest retrieves the key and secondly getValue() method that retrieves the value corresponding to the given key.Īdding Entry with Duplicate Key in HashMap In Step 4 we have used two methods, as shown. ![]() In this for loop we have used method entrySet(), which returns a Set view of the mappings contained in the HashMap object and the Map.Entry is an Interface that enables you to work with a map entry easily by which key-value pairs are retrieved one by one, and are displayed in next step. In Step 3, we have used for each loop of following syntax to retrieve the values from the HashMap object.In Step 2, we have used put method to add key value pair in the data structure that we have created in step 1.In Step 1, we have created an object of HashMap collection, As we have already discussed HashMap has key value pair, so obviously we have to define the type of key and value, We have defined Key of Integer type, and Value of String type. ![]() out.println(map.getKey()+" "+map.getValue()) Step 4: Using getKey and getValue methods to retrieve key and corresponding value Step 3: Displaying key value pairs using for loop
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |