Sunday, 12 May 2013

How to iterate over a Map in Java?

Just to revise basic of Map go through it demo code. We will use the same piece of code and iterate over it.Purpose of this post is to demonstrate how can we iterate over a Map. We know Map interface does not implement Collection interface and hence we cannot just say someMap.iterator() . To revise Iterators refer to the post on understanding Iterators.Lets see then how do we iterate over a Map.

Java Code : 

package testCodes;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class MapDemo {

    public static void main(String args[]) {
        Map<String, String> persononalData = new HashMap<String, String>();
        // Populating Map with data
        persononalData.put("Name", "John");
        persononalData.put("Country", "USA");
        persononalData.put("Gender", "Male");
        persononalData.put("Age", "18");
        Iterator<Map.Entry<String, String>> mapIterator = persononalData
                .entrySet().iterator();
        while (mapIterator.hasNext()) {
            Map.Entry<String, String> keyValuPair = mapIterator.next();
            System.out.println("Key is " + keyValuPair.getKey());
            System.out.println("Value is " + keyValuPair.getValue());
        }
    }
}

output :


Understanding the code : 

 As Map is not a Collection we cannot use .iterator() function on it. What we do is we create a set of Entry objects and iterate over it. Internally key-value pair are stores in Entry objects in the Map. We then get iterator of this set and iterate over it. Entry object has key and values stores in it and we can extract them using .getKey() and .getValue() methods.

Smarter Way : 

        for (Map.Entry<String, String> keyValuePairs : persononalData
                .entrySet()) {
            System.out.println("Key is " + keyValuePairs.getKey()
                    + "and value is " + keyValuePairs.getValue());
        }

This is a bit smarter way to do the same iteration. Internally it does the same thing i.e use a iterator and iterate over the Entry set.This may look a bit complex for beginners. So method mentioned above is recommended.

 What if I only wish to iterate over keys or just values?

             Yes there is a way to specifically iterate over keys and values in Map. The .keySet()  function will return a set of keys where as .values() function will return Collection of values.Note once you have the Set you can get it's iterator and iterate over it's values.

Iterate over keys : 

        for (String key : persononalData.keySet()) {
            System.out.println("Key is " + key);
        }

Output : 

Key is Name
Key is Age
Key is Gender
Key is Country

Iterate over Values : 

        for (String value : persononalData.values()) {
            System.out.println("Values is " + value);
        }

Output : 

Values is John
Values is 18
Values is Male
Values is USA

Note : Keys in a Map are unique and hence .keySet() will return a set. Two different keys can have same value and hence values can't form a set(Values in a set are unique) and hence what you get from .values() is a Collection.

Related Links

Simple Map example in Java.

We have learned enough theory on Collections. We also saw a working demo code for ArrayList. In last post we saw why Map interface does not implement Collection framework and in the coming posts we will see how to iterate over the data in Map. But for now lets see a demo code of Map.

Java Code demonstrating Map usage

Code :

package testCodes;

import java.util.HashMap;
import java.util.Map;

public class MapDemo {

    public static void main(String args[]) {
        Map<String, String> persononalData = new HashMap<String, String>();
        // Populating Map with data
        persononalData.put("Name", "John");
        persononalData.put("Country", "USA");
        persononalData.put("Gender", "Male");
        persononalData.put("Age", "18");
        // Printing Map
        System.out.println("Map is " + persononalData);
        // removing data from Map
        persononalData.remove("Gender");
        // Printing Map
        System.out.println("Map is " + persononalData);
        if (Integer.valueOf(persononalData.get("Age")) < 18) {
            System.out.println("You are a minor");
        } else {
            System.out.println("You are a Major");
        }
    }
}

Output :

Understanding the Code :

We create a Map named persononalData to store personal information of some person named John. Note the generics used. Both key-value are of type String. At a later point of time if you try to put another data type(say int) then that is not allowed. You must always decide on the data structure before you start writing you actual code.In this case I am going to store everything as String.
     We then start populating data. We add Name, Country, Age and Gender.Note the function is put(key,value) unlike add(element) in Collections.We then print the Map. Note when we say System.out.println(someMap) internally toString() method is invoked on the corresponding object and is printed to standard output.
   Next we remove an element using .remove(key) method.Again we print out the Map to see the difference. Check out the output screen shot provided above.

Note : All keys in the Map must be Unique i.e you cannot store two different values for the same key. Lets say you do someMap.put("Name","John") and then again you say someMap.put("Name","Sam") then Sam will overwrite John and when you extract data by get("Name") you will get Sam and not John.

  Next we extract age of the person using .get("Age") method. Note this will return you a String. But for comparison purpose you need an integer and hence we convert String to an int using Integer.ValueOf(SomeString) method.In our case age is 18 and hence age<18 will evaluate to be false and else part will get executed. Hence the output shown.

   Hope basic operations in Map are clear. In next post we will see how to iterate over Map to manipulate it's data.

Related Links

Why Map is not a true Collection?

We saw what are Collections in Java. If you recall the diagram from that post Map does not form a part of Collection though it comes under Collection framework. In more technical terms Map interface does not implement Collection interface. Knowing this the question that naturally comes in mind is why so? Why can't Map be a part of Collection frame work? Let us see the explanation.

Reason for Map interface not extending Collection interface

  • If you look at the respective data structure you can easily guess why Map is not a part of Collection. Each Collection stores a single value where as a Map stores key-value pair. So methods in Collection interface are incompatible for Map interface.For example in Collection we have add(Object o). What would be such implementation in Map. It doesn't make sense to have such a method in Map. Instead we have a put(key,value)  method in Map.
  • Same argument goes for addAll(), remove(), removeAll() methods. So the main reason is the difference in the way data is stored in Map and Collections.
  • Also if you recall Collection interface implemented Iterable interface i.e any interface with .iterator() method should return an iterator which must allow us to iterate over the values stored in the Collection. Now what would such method return for a Map? Key iterator or a Value iterator? This does not make sense either.
There are ways in which we can iterate over keys and values stores in a Map and that is how it is a part of Collection framework.Do not get confuse here. Let me repeat this - Map is a part of Collection framework but it does not implement Collection interface. We will see in next few posts how Map works internally(that's really an interesting topic) and also how we manipulate data in it.

Just to recall the Collection framework refer to the following diagram -




A little fun with Linux command line!


Yes that's the picture I posted on LinuxForGeeks today on the special occasion of Mother day. Let me take this occasion to clarify that people using CLI(Command line interface) are not some geeks who know something special which common people don't. Once you start using CLI you will know how much fun it is. For now let me introduce some cool commands.

Here are some command you may enjoy in your spare time -

  1. fortune
    Fortune is a simple program that displays s pseudo random message from a database of quotations that first appeared in version 7 Uiux. Just type fortune in the CLI and see the various messages that are displayed.To install fortune type the following in CLI - sudo apt-get install fortune-mod

    Some examples are as follows -

    You get the point. For more info refer to its man page.Some options that you can use with the command are -

     
  2.  cowsay
    Cowsay is a program(written in Perl) which generates ASCII picture with of a cow with a message It can also generate pictures using pre-made images of other animals, such as Tux the Penguin, the Linux mascot.To install cowsay just type in CLI - sudo apt-get install cowsay

    Example -

    You can use -f  tux option to get a tux instead of a cow.
    That's not it. You can combine fortune and cowsay commands to have a bit more fun.Type the following in your CLI
    fortune | cowsay -f tux
  3.  
  4. espeak
    eSpeak is a compact open source software speech synthesizer for Linux.
    Just type  espeak 'Hello World' in your CLI and you will hear the voice saying the argument supplied(Hello World). This is the default program installed on Ubuntu.
    It can also read from a text file supplied with -f argument. For more info you can refer eSpeakCommands.
t> UA-39527780-1 back to top