In this example we will show two ways to traverse a HashMap object, getting the key and getting the mapping relationship, as shown below.
Source Code
1)
package com.beginner.examples;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class CreateHashMapAndIterate {
/**
* @param args
*/
public static void main(String[] args) {
HashMap hMap=
new HashMap();
//add key,value
hMap.put("Name", "Tom");
hMap.put("Age", "20");
hMap.put("Sex", "man");
hMap.put("Hobby", "play basketball");
//The first traversal method,The first traversal method stores
//the keys of this collection into the Set Set and traverses the Set Set
Set keys=hMap.keySet();
Iterator iterator=keys.iterator();
while(iterator.hasNext())
{
String key=iterator.next();
String value=hMap.get(key);
System.out.println(key+"------"+value);
}
//Second, get the mapping class for this collection of hashmaps
System.out.println("----------------------");
Set<Map.Entry> entry=hMap.entrySet();
Iterator<Map.Entry> it1=entry.iterator();
while(it1.hasNext())
{
Map.Entry e=it1.next();
String key=e.getKey();
String value=e.getValue();
System.out.println(key+":::::::::"+value);
}
}
}
Output:
Name------Tom
Age------20
Hobby------play basketball
Sex------man
----------------------
Name:::::::::Tom
Age:::::::::20
Hobby:::::::::play basketball
Sex:::::::::man
2)
package com.beginner.examples;
import java.util.HashMap;
public class DeleteAndChange {
/**
* @param args
*/
public static void main(String[] args) {
HashMap asiccMap=new HashMap();
//add
asiccMap.put('a', 90);
asiccMap.put('b', 98);
asiccMap.put('c',99);
asiccMap.put('d', 100);
//alter value returns the replaced value
System.out.println(asiccMap.put('a', 97)+" alter after: "+asiccMap.get('a'));
//Delect Returns the deleted value
System.out.println(asiccMap.remove('d')+" remove after: "+asiccMap.get('d'));
}
}
Output:
90 alter after: 97
100 remove after: null
References
Imported packages in Java documentation: