Three ways to traverse a map in Java

import java.util.Collection;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;


public class TestHashMap {

/************ Three ways to traverse the map ************************/

public static void main(String[] args) {
TestHashMap test =new  TestHashMap();
test.function();
}

public void function() {

HashMap<String,Object> hm = new HashMap<>();
hm.put("int", 23);
hm.put("boolean", true);
hm.put("String", "哈哈");
hm.put("char", 'z');
hm.put("s", null);
hm.put(null, null);

System.out.println(hm.size());

/*********The first way to traverse Get the set of all keys in the set *************/
// Set<String> key = hm.keySet() ;
// for(String every:key) {
// System.out.println(every+" "+hm.get(every));
// }

/*********Second traversal method Get the collection of all values ​​in the collection *************/
// Collection<Object> obj = hm.values() ;
// // for(Object every:obj) { // System.out.println(every); // }




/****The third traversal method wraps each set of key-value pairs into an Entry object and puts it into a set to return **/
Set<Entry<String,Object>> entry = hm.entrySet();
for(Entry<String,Object> every: entry) {
System.out.println(every.getKey()+" "+every.getValue());
}


}

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325580593&siteId=291194637