UAB -> ENG -> [ ECE / ECE News & Notes ] -> [ DGreen / DGreen Intranet ] -> Java Documenation Style and Code Examples -> Explore HashMap

Explore HashMap

Here is a small example program to walk through all items of a HashMap since walking through by 0, 1, 2, … does not exist as it did with ArrayList. Code ByteCode

// Exploring a HashMap

import java.util.*;

public class ExploreHashMap {
  public static void main(String[] args) {

    HashMap<String, String> sm = new HashMap<>();

    sm.put("key1", "value1");
    sm.put("key2", "value2");
    sm.put("key3", "value3");

    // when I need to go through all of the items, I can get a list
    // of all the keys with 
    
    Set<String> keys = sm.keySet();

    // I can then walk through the list of keys to visit each object in
    // the hashmap
    
    // for each key in keys

    for(String key : keys) {
      // find a value by its key in O(1) processing time
      String value = sm.get(key);   // could be remove, etc.
      System.out.println("key = " + key + " value = " + value);
    }
  }
}