In this article we will show you the solution of iterate hashmap in java, Java allows you a number of different ways to iterate a Map. Keep in mind that since the Map interface is not a component of Collection, we cannot simply iterate across maps using iterators.
Java provides the Map interface for all maps. Even though a map is not a collection, it is still seen as a collection.
Since a Map does not extend the Collections interface, it is a separate interface.
We will now discuss the idea of how to iterate hashmap in java with an example.
Step By Step Guide On Iterate Hashmap In Java :-
Code 1
import java.util.Map; import java.util.HashMap; class TalkersCode { public static void main(String[] arg) { Map<String,String> map = new HashMap<String,String>(); map.put("Capgemini", "$500 billion"); map.put("Cognizant", "$30.5 billion"); map.forEach((k,v) -> System.out.println("Company: "+ k + ", Net worth: " + v)); } }
Code 2
import java.util.*; class talkerscodeIteration { public static void main(String[] arg) { Map<String, String> map = new HashMap<String, String>(); map.put("Amruta", "Shahane"); map.put("Harry", "Potter"); map.put("Ron", "Weasley"); for (String name: map.keySet()) //iteration over keys { //returns the value to which specified key is mapped String lastname=map.get(firstname); System.out.println("Key: " + name + ", Value: " + lastname); } } }
- The "Map" and "HashMap" classes from the "java.util" package are imported in the first line of code.
- The "TalkersCode" class is developed.
- The main technique is developed.
- The "map" variable is given a fresh instance of the HashMap class. The data type "Map" is supplied to denote that the map's keys and values are both Strings.
- Using the put() method, two key-value pairs are added to the map. "Capgemini" is the first key, while "$500 billion" is the associated value. The value for the second key, "Cognizant," is "$30.5 billion."
- The "map" object receives a call to the forEach() method. Two parameters, k and v, which stand for the key and value of each entry in the map, are supplied as arguments to the lambda expression.
- The company name (stored in "k") and its associated net worth (stored in "v") are concatenated into a string using the lambda expression. This code prints its results to the console.
Conclusion :-
As a result, we have successfully learned how to iterate hashmap in java with an example.
Hash maps are used when it is necessary to store data as key-value pairs so that each element's value may be retrieved using its corresponding key.
I hope this article on iterate hashmap in java helps you and the steps and method mentioned above are easy to follow and implement.