Java equivalent of PHP foreach ($array as $key=>$val)

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

About Cameron
I'm a final year Computer Science/Information Systems major. Already finished my BA in Politics/Philosophy. I do web and software freelance on the side, while I finish studying. Hoping to be self-employed by the end of my degree, otherwise off into the real-world I go....

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: