CodesJava

Easy learning with example program codes

Map.Entry interface in java


Map.Entry interface:

Map.Entry interface provides the facility to work with a map entry. The entrySet( ) method of the Map interface returns the set of map entries i.e. set of Map.Entry objects.

Commonly used methods of Map.Entry interface:

1. equals(Object obj): Returns true if specified object is equals to this map otherwise returns false.

Syntax: public boolean equals(Object obj).

2. getKey(): It returns the key of the calling map entry.

Syntax: Object getKey()

3. getValue(): It returns the value of the calling map entry.

Syntax: Object getValue()

4. hashCode(): It returns the hash code of the calling map entry.

Syntax: int hashCode()

5. setValue(Object v): It sets the value of the calling map entry to v. It throws NullPointerException if v is null.

Syntax: Object setValue(Object v)

 A simple example of HashMap class to explain few methods of Map.Entry interface.

 HashMapTest.java

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
 
/**
 * This class is used to show the HashMap functionality.
 * @author codesjava
 */
public class HashMapTest {
	public static void main(String args[]){
		//Create HashMap object.
		Map hashMap = new HashMap();
 
		//Add objects to the HashSet.
		hashMap.put(4, "Roxy");
		hashMap.put(2, "Sunil");
		hashMap.put(5, "Sandy");
		hashMap.put(1, "Munish");
		hashMap.put(3, "Pardeep");
 
		//Print the HashMap object.
		System.out.println("HashMap elements:");
		System.out.println(hashMap);
 
		//Get iterator
		Set set=hashMap.entrySet();  
		Iterator iterator=set.iterator();  
 
		//Print the HashMap elements using iterator.
		System.out.println("HashMap elements using iterator:");
		while(iterator.hasNext()){
		   Map.Entry mapEntry=(Map.Entry)iterator.next();  
		   System.out.println("Key: " + mapEntry.getKey() + ", " +
		   		"Value: " + mapEntry.getValue());  
		}  
	}
}

Output:

HashMap elements:
{1=Munish, 2=Sunil, 3=Pardeep, 4=Roxy, 5=Sandy}
HashMap elements using iterator:
Key: 1, Value: Munish
Key: 2, Value: Sunil
Key: 3, Value: Pardeep
Key: 4, Value: Roxy
Key: 5, Value: Sandy

Download this example.
 
Next Topic: SortedMap interface in java with example.
Previous Topic: Map interface in java with example.

Sign Up/ Sign In
Ask a Question


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki