Java equivalent of PHP foreach ($array as $key=>$val)
Tuesday, June 15th, 2010 Leave a comment
As a follow up to my previous post, where I complained that there was no easy way in Java to deliver PHP’s foreach ($array as $key=>$val) functionality I have an update. Using Java’s HashMap or LinkedHashMap types, the same result can be achieved. The difference between the two is that LinkedHashMap retains the order of the array.
import java.util.*; class Foo { public static void main(String[] args) { Map<String, String> stateMap = new LinkedHashMap<String, String>(); stateMap.put("ALABAMA", "AL"); stateMap.put("ALASKA", "AK"); // ... stateMap.put("WYOMING", "WY"); for (Map.Entry<String, String> state : stateMap.entrySet()) { System.out.printf("The abbreviation for" + state.getKey() + " is " + state.getValue() + "\n"); } } }
This utilises a HashMap which enables a key value pair to be defined and thereby replicates PHP’s foreach ($array as $key=>$val) functionality.
(sourced via stackoverflow.com)
recent comments