The Map.Entry interface enables you to work with a map entry.
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.
Following table shows the list of methods available in Map.Entry interface:
NOTE: A ClassCastException is thrown if v is not the correct type for the map. A NullPointerException is thrown if v is null and the map does not permit null keys. An UnsupportedOperationException is thrown if the map cannot be changed.
Example:
package com.sample.javase.testing;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
public class SortedMapInterfaceExample {
/**
* @param args
*/
public static void main(String[] args) {
SortedMap<String, String> sortedMap = new TreeMap<String, String>();
sortedMap.put("oop1", "java");
sortedMap.put("oop2", "c++");
sortedMap.put("oop3", "objective-c");
System.out.println(sortedMap);// it maintains ascending order.
System.out.println("first key is" + sortedMap.firstKey());
System.out.println("Last key is " + sortedMap.lastKey());
/**
* Following lines of code specifies hoe to get the map values form
* iterator. For this first we need to get entry set or key set from
* map.Here we are using entryset() method.
*/
Set set = sortedMap.entrySet();
for (Iterator iterator = set.iterator(); iterator.hasNext();) {
Map.Entry entry = (Entry) iterator.next();
System.out.println("key is " + entry.getKey());
System.out.println("value is " + entry.getValue());
}
/**
* Following lines of code specifies hoe to get the map values form
* iterator. For this first we need to get entry set or key set from
* map.Here we are using keyset() method.
*/
Set set2 = sortedMap.keySet();
for (Iterator iterator = set2.iterator(); iterator.hasNext();) {
Object object = (Object) iterator.next();
System.out.println("key is " + object + "value is " + sortedMap.get(object));
}
}
}
No comments:
Post a Comment