Is it possible to write a "foreach" function in Java?

java

Solution

Yes you can:

List<String> ls = new ArrayList();
ls.add("Hello");
ls.add("world");
//your foreach sentence
for(String s : ls) {
    System.out.println(s);
}

This work with another classes too.

UPDATE

When you traverse a List (array or linked list) the index would be the index. You will need to use an alternative integer to hold the index:

List<String> ls = new ArrayList();
ls.add("Hello");
ls.add("world");
//your foreach sentence
int index = 0;
for(String s : ls) {
    System.out.println("index: " + index);
    System.out.println(s);
    //put your logic here...
    //at the end, update the index manually
    index++;
}

If you need to traverse a Map (key, value based structure) then you should use the method described by @LukasEder (adapting his code):

Map<K, V> array = new HashMap<K, V>();
for (Entry<K, V> entry : array.entrySet()) {
    // You have to explicitly call your callback. There is no "callback-syntax"
    // to the Java "foreach" loop
    System.out.println("key: " + entry.getKey());
    System.out.println("value: " + entry.getValue());
    //put your logic here...
}

Problem

In PHP, one can do `foreach($array as $key=>$value){//codes`. Is it possible to create a function in Java to do `foreach(arr,function(key,value){//codes});`? I'm not very good at Java. For the function to work, it must accept all data types. Also, I'm not sure if callback functions can be used in Java. P.S. "Not possible" is a valid answer, thanks!

Original source