It is not an ordered collection which means it does not return the keys and values in the same order in which they have been inserted into the HashMap. The iterator returned by HashMap is fail-fast.
HashMap Example
import java.util.*; public class HashMapExample { public static void main(String args[]) { // Declaring a HashMap of Integer keys and String values HashMap<Integer, String> hashmap = new HashMap<Integer, String>(); hashmap.put(1, "Value1"); hashmap.put(2, "Value2"); hashmap.put(3, "Value3"); hashmap.put(4, "Value4"); hashmap.put(5, "Value5"); System.out.println("HashMap contains: "+hashmap); /* Get values based on key*/ String var= hashmap.get(2); System.out.println("Value at key 2 is: "+var); /* Remove values based on key*/ hashmap.remove(3); System.out.println("Map keys and values after removal:"); Set set = hashmap.entrySet(); Iterator it = set2.iterator(); while(it.hasNext()) { Map.Entry pair = (Map.Entry)it.next(); System.out.print("Key is: "+pair.getKey() + " and Value is: "); System.out.println(pair.getValue()); } } }
Output
HashMap contains: {1=Value1, 2=Value2, 3=Value3, 4=Value4, 5=Value5} Value at key 2 is: Value2 Map keys and values after removal: Key is: 1 and Value is: Value1 Key is: 2 and Value is: Value2 Key is: 4 and Value is: Value4 Key is: 5 and Value is: Value5
HashMap Tutorials
Below is the list of tutorials on HashMap class.HashMap Basics
- How to iterate HashMap in Java
- Get Size of HashMap
- How to check if HashMap is Empty or not
- Sort HashMap by Keys and Values
- Remove Key-Value Mapping from HashMap
- Remove all Key-Value Pairs from HashMap
Differences
- HashMap vs Hashtable
- HashMap vs ConcurrentHashMap
- HashMap vs HashSet
- HashMap vs ArrayList
- HashMap vs TreeMap
- HashMap vs WeakHashMap
- HashMap vs IdentityHashMap
Internal Working
Serialize/Synchronize
Get/Search
Other Tutorials
Reference : HashMap Oracle docs