Wednesday, March 05, 2014

Hashmap in Java Using Generics

package helloworld;

import java.util.*;

public class CollectionsTest {
public CollectionsTest() {
super();
}

public static void main(String[] args) {

// keys are Strings
// objects are also Strings
Map map = new HashMap();
map.put("Nokia", "Mobile");
map.put("Jdeveoper", "Java");
map.put("Lennove", "PC");

//One way to display the values
Iterator i=map.entrySet().iterator();
while (i.hasNext())
{System.out.println(i.next());}
// Second way to display the value
for (String key : map.keySet()) {
System.out.println(key + " " + map.get(key));
}

// add and remove from the map
map.put("Galaxy", "Samsung");
map.remove("Nokia");

// write again to command line
for (String key : map.keySet()) {
System.out.println(key + " " + map.get(key));
}
}



}


The above code will give below result

Lennove=PC
Jdeveoper=Java
Nokia=Mobile
Lennove PC
Jdeveoper Java
Nokia Mobile
Lennove PC
Jdeveoper Java
Galaxy Samsung


Here the results are displayed using two methods

First is the iterator method which gets the object and displays the data.

The second is the for loop where in keySet is used to get the map data and display it.

There are two different methods entrySet() and the keySet()

Lets try to understand them by modifying the code

package helloworld;

import java.util.*;

public class CollectionsTest {
public CollectionsTest() {
super();
}

public static void main(String[] args) {

// keys are Strings
// objects are also Strings
Map map = new HashMap();
map.put("Nokia", "Mobile");
map.put("Jdeveoper", "Java");
map.put("Lennove", "PC");

//One way to display the values
Iterator i=map.keySet().iterator();
while (i.hasNext())
{System.out.println(i.next());}

}

}

Now you can observe that the iterator is retrieve using the keySet this will pass on the map for key only so if you will run this code you will get following result

Lennove
Jdeveoper
Nokia


However when we do an entrySet it returns a map which has all the key-value.

No comments: