Thursday, 3 November 2016

What is Map.Entry In Java ?

Previously we have discussed about

Here we know about Map.Entry in Java, but before that we must know What is Map Interface in Java ? and What is Collection Interface in Java ?
Interface Map.Entry<K,V>

All Known Implementing Classes:
AbstractMap.SimpleEntry, AbstractMap.SimpleImmutableEntry

Enclosing interface:
Map<K,V>

Declaration of Map.Entry:
public static interface Map.Entry<K,V>

Map.Entry interface enables you to work with a map entry. This interface help us to iterate over Map classes.The entrySet( ) method declared by the Map interface returns a Set containing the map entries.Each of these set elements is a Map.Entry object.

JDK 8 adds two static methods. The first is comparingByKey( ), which returns a Comparator that compares entries by key. The second is comparingByValue( ), which returns a Comparator that compares entries by value.

Method Summary of Map.Entry:

Modifier and Method Name
Description
boolean equals(Object o)
Compares the specified object with this entry for equality.
K getKey()
Returns the key corresponding to this entry.
V getValue()
Returns the value corresponding to this entry.
int hashCode()
Returns the hash code value for this map entry.
V setValue(V value)
Replaces the value corresponding to this entry with the specified value (optional operation).
      
Example of Map.Entry:

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

public class MapEntryExample {

public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("India", 100);
map.put("Japan", 101);
map.put("Russia", 103);
map.put("USA", 105);
map.put("UK", 108);

System.out.println("Map Size() : "+map.size());

System.out.println("\nAccessing Map through Iterator : ");
Iterator itr = map.entrySet().iterator();
while(itr.hasNext()){
Map.Entry me = (Map.Entry)itr.next();
System.out.println(me.getKey()+"\t"+me.getValue());
}

System.out.println("\nAccessing Map through forEach : ");
for(Map.Entry en : map.entrySet()){
System.out.println(en.getKey()+"\t"+en.getValue());
}

}


}

Program Output:

Map Size() : 5

Accessing Map through Iterator :
USA 105
Japan 101
UK 108
India 100
Russia 103

Accessing Map through forEach :
USA 105
Japan 101
UK 108
India 100
Russia 103



Blog Author - Pushkar Khosla,
Software Developer by Profession with 3.0 Yrs of Experience , through this blog i'am sharing my industrial Java Knowledge to entire world. For any question or query any one can comment below or mail me at pushkar.itsitm52@gmail.com.

This blog is all about to learn Core Java ,Interview Programs and Coding tricks to polish your Java Knowledge. If you like the content of this blog please share this with your friends.



No comments:

Post a Comment