Four Java methods for traversing Map

  • 2021-06-28 12:28:21
  • OfStack

Choose the best fit


import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
 * Created by song on 2019/1/17.
 **/
public class MapT {
  public static void main(String[] args) {
    Map<Integer,String> map=new HashMap<>();
    map.put(1," No. 1 individual ");
    map.put(2," No. 2 individual ");
    map.put(3," No. 3 individual ");
    map.put(4," No. 4 individual ");
    // No. 1 Species: First available key Value of   Then pass key Worth it value value 
    Set<Integer> set=map.keySet();// The generic here is key Worth Generic 
    for(Integer integer:set){
      System.out.println(integer+"->"+map.get(integer));//key->value
    }
    // No. 2 species : adopt Map.values() Traverse all value But it cannot be traversed key
    for(String s:map.values()){
      System.out.println(s);
    }
    // No. 3 species : adopt Map.entrySet Using Iterators iterator ergodic key and value
    Iterator<Map.Entry<Integer,String>> iterable=map.entrySet().iterator();
    while(iterable.hasNext()){
Map.Entry<Integer,String>entry=iterable.next();
      System.out.println(entry.getKey()+"->"+entry.getValue());
    }
    // No. 4 species : Direct Pass Map.entrySet ergodic key and value
    // Most common 
    for(Map.Entry<Integer,String> entry:map.entrySet()){
      System.out.println(entry.getKey()+"->"+entry.getValue());
    }
    // Note: Map.Entry Method Interpretation 
    //Map.Entry yes Map Declared 1 Internal interface, which is generic and defined as Entry<K,V> .It represents Map In 1 Entities ( 1 individual key-value Yes) 
  }
}

summary


Related articles: