Example of Java traversing Map keys values and getting the size of Map

  • 2020-06-01 09:38:32
  • OfStack

Map reads key-value pairs, and Java traverses two implementations of Map

The first method is to get the set collection of key according to the keyset () method of map, and then traverse map to get the value value


import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
public class HashMapTest2
{
 public static void main(String[] args)
 {
 HashMap map = new HashMap();
 
 map.put("a","aaaa");
 map.put("b","bbbb");
 map.put("c","cccc");
 map.put("d","dddd");
 
 Set set = map.keySet();
 
 for(Iterator iter = set.iterator(); iter.hasNext();)
 {
  String key = (String)iter.next();
  String value = (String)map.get(key);
  System.out.println(key+"===="+value);
 }
 }
}

The second way is to use Map.Entry to get:


import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class HashMapTest4
{
 public static void main(String[] args)
 {
 HashMap map = new HashMap();
 
 map.put("a","aa");
 map.put("b","bb");
 map.put("c","cc");
 map.put("d","dd");
 
 Set set = map.entrySet();
 
 for(Iterator iter = set.iterator(); iter.hasNext();)
 {
  Map.Entry entry = (Map.Entry)iter.next();
  
  String key = (String)entry.getKey();
  String value = (String)entry.getValue();
  System.out.println(key +" :" + value);
 }
 }
}

Get the Map size method:


public static void main(String[] args) {

  Map map = new HashMap();

  map.put("apple", " Fresh apples ");   // Add data to the list 

  map.put("computer", " A computer with good configuration ");  // Add data to the list 

  map.put("book", " A mountain of books ");   // Add data to the list 

  System.out.println("Map The set size is: "+map.size());

}

Related articles: