Skip to content

Tag: foreach

Iterating over a HashMap

Iterating over a HashMap using the enhanced loop (foreach) in Java is a good way to keep your code smaller, more legible and usually more semantically coherent.

import java.util.HashMap;
import java.util.Map;

class Foo {}

public class Main {
	
   public static void main(String args[]){
      Map mHash;
		
      mHash = new HashMap();
      mHash.put((byte)1, new Foo());
      mHash.put((byte)2, new Foo());
      mHash.put((byte)3, new Foo());
		
      for(Foo f: mHash.values()){
         System.out.println(f.toString());
      }
   }
}