How to iterate in a HashMap in Java

in java •  7 years ago 

There are many applications in the information have to be processed or organized in different ways.

In Java there is a way to organize data in keys and values. To every key corresponds a value and this way or organizing data is called hash table . There is more on this on wikipedia https://en.wikipedia.org/wiki/Hash_table

Schermata 2017-10-18 alle 12.00.52.png

The Java implementation of an hash table is the HashMap which is implemented in Java Collection API. In this guide we see how to use it. As an example for the data to insert in the HashMap you can take names and ages of a group of persons.

For example let's say we have the following dataset

name,age
John,32
Jihm,35
Dan,45

You can read this information from a file or add it to your HashMap manually for example :


Map<String, Integer>map = new HashMap<String, Integer>();
map.put("John", 32);
map.put("Jihm", 35);
map.put("Dan", 45);

If you want your keys ordered in alphabetic order then use a TreeMap instead :


Map<String, Integer>map = new TreeMap<String, Integer>();

Now that we have the data we can iterate by using a for loop


for(String s : map.keySet()){
// we can use the method get(key) to access to the values corresponding to that key
System.out.println(s+", "+map.get(s));
}

So enjoy using HashTables implementation in Java.

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

So easy!