Enumerate all the keys " ) įinal Enumeration e = Collections.enumeration(hm. ("key: " entry.getKey() ", value: " entry.getValue()) Using a for loop to iterate through a HashMap In the code below, hashmap.entrySet () is used to return a set view of the mapped elements. Map.Entry entry = (Map.Entry) entrysetIterator.next() Iterator entrysetIterator= hm.entrySet().iterator() Iterate all the key/value pairs returned by entrySet() method\n " ) Iterator keysetIterator = hm.keySet().iterator() Iterate all the keys returned by keySet() method\n ") Loop all the key/value pairs in the HashMap returned by entrySet() method\n " ) Loop all the values in the HashMap returned by values() method\n" ) Loop all the keys in the HashMap returned by keySet() method \n ") ("\nUsing Enhanced for loop in Java 1.5") In the following code, you can find 6 ways to iterate / enumerate all the elements (strings) in the the hashmap Finally Traversing HashMap using Enumerationįinal Enumeration e = Collections.enumeration(hm.keySet()) – returns an enumeration over all the keys. Collection vs = hm.values() – Values to Collection object.Ĥ. Iterator> entrysetIterator = es.iterator() ģ. Set> es = hm.entrySet() //key/value pair to Set Set keys = hm.keySet() // hashmap keys to Set. Once it is converted to Set or Collection object, you can either use iterator() method or enhanced for-loop of java 1.5 to iterate over all the keys or values.ġ. Now let us see lines to convert Map to Set or Collection object. The above Set or collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa. values() – returns a Collection object view of the the values contained in the map. entrySet() – returns a Set object referencing the key / object pairs (an object of type Map.entry) stored in the map. keySet() – returns a Set object referencing the keys contained in the map.Ģ. But the Map interface provides 3 methods to obtain a collection view (Set or Collection object) of the contents of a map.ġ. Like Hashtable, HashMap and TreeMap does not provide the methods elements() and keys() to return enumeration of the values and keys respectively to process all the elements. There are number of ways to traverse / process all the elements in the Map.
0 Comments
Leave a Reply. |