Java 8 Iterate Over HashMap

You have a few options in dealing with HashMap with the introduction of Java 8 Streams and Lambda Expressions. Prior to Java 8, iterating over HashMap was exclusively done with a for loop. The Stream.forEach() method has replaced that functionality.

We start off by defining a new HashMap called statesHashMap. Next we add the two digit state codes and the full state name for a few entries. You can then print only the keys, only the values, or both keys and values of the HashMap.

//JavaCodeDepot.com Sample

//Create new HashMap that has key/value both set to String
HashMap<String,String> statesHashMap = new HashMap<String,String>();
		
//Add some values to our String HashMap
statesHashMap.put("NC", "North Carolina");
statesHashMap.put("SC", "South Carolina");
statesHashMap.put("NY", "New York");
statesHashMap.put("FL", "Florida");
statesHashMap.put("TX", "Texas");


Print Out HashMap Keys

//Print out HashMap keys
statesHashMap.keySet().stream().forEach(System.out::println); 

Output:

SC
TX
NC
FL
NY


Print Out HashMap Values

//Print out HashMap values
statesHashMap.values().stream().forEach(System.out::println);

Output:

South Carolina
Texas
North Carolina
Florida
New York


Print Out HashMap Keys & Values

statesHashMap.entrySet()
        	 .stream()
        	 .forEach(entry -> System.out.println("Key="+entry.getKey()+" value="+entry.getValue()));

Output:

Key=SC value=South Carolina
Key=TX value=Texas
Key=NC value=North Carolina
Key=FL value=Florida
Key=NY value=New York


See more Java 8 Stream Samples that highlight other Stream Operations in Java 8.

Add a Comment

Your email address will not be published. Required fields are marked *