
How we can use Map in java collection?

The Map interface maps unique keys to value means it associate value to unique keys.
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class MapExample {
public static void main(String[] args) {
Map mp = new HashMap();
mp.put(new Integer(2), "Two");
mp.put(new Integer(1), "One");
mp.put(new Integer(3), "Three");
mp.put(new Integer(4), "Four");
Set st = mp.entrySet();
Iterator it = st.iterator();
while (it.hasNext()) {
Map.Entry m = (Map.Entry) it.next();
int key = (Integer) m.getKey();
String value = (String) m.getValue();
System.out.println("Key :" + key + " Value :" + value);
}
}
}
Output:
Key :1 Value :One Key :2 Value :Two Key :3 Value :Three Key :4 Value :Four
Description:- The above example demonstrates you the Map interface. Since Map is an interface, you need to instantiate a concrete implementation of the interface in order to use it. Here Map is implemented by its subclass HashMap. Using the put method, we have added elements to key and value pair. Now to display the key and values, we have called getKey() and getValue() methods that are defined by Map.Entry.
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.