mapping() is used to make sure we get the keys of the original map as the value in the new map, whithout this we would get the entries as values. By doing this, we can get the highest value by using lastEntry(). The HashMap class has a get() method that takes a key and returns the value mapped to this key. By stating that it should collect into a TreeMap, it will be sorted according to its keys. Key: 7 Value: Plum Retrieve a Specific Value HashMap : It is the direct implementation class of Map interface (i.e. getValue()) Īdding the method above to your code will print the following output in your console: Key: 1 Value: Orange view all items with an iteratorįor ( HashMap. This method employs the Map interface that the HashMap class implements. If you want to retrieve all the data individually, then you can use the for method that allows you to traverse through the HashMap and print each value and its corresponding key. This is a feature that puts HashMaps ahead of other data structures such as the Array data structure that only support linear storage. key This is the key whose associated value is to be returned Return Value The method call returns the value to which the specified key is mapped, or null if this map contains no mapping for the key. Though each value was randomly added to the HashMap, from the output you will see that HashMap stores the values in ascending order, based on the key assigned to each value. So in short you do the following: Enumeration enumeration new IteratorEnumeration (hashMap.keySet ().iterator ()) Alternatively, if you (for some reason) dont want to include commons-collections, you can implement this adapter yourself. View all the items as an objectĪdding the line of code above to the Main class, prints the following output in the console: Adapter to make an Iterator instance appear to be an Enumeration instances. If you want to retrieve the data as an object, you can simply access the HashMap object, which in the example below is fruitsMap.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |