Modifier 'for'
Method modifier 'for' enables us to declare and call "loop-like" methods.
static for void eachEntry(int[] values, { int ==> void } block) {
for (int p : values) {
block.invoke(p);
}
}
public static void main(String[] args) {
int[] v = { 2, 3, 5, 7, 11 };
for eachEntry(int i : v) {
System.out.println(i);
if (i > 3) {
break;
}
}
}
For example, we can declare a method that iterates through a map:
static for <K, V> void eachMapEntry(Map<K, V> dict,
{ K, V ==> void } block) {
for (Map.Entry<K, V> entry : dict.entrySet()) {
block.invoke(entry.getKey(), entry.getValue());
}
}
public static void main(String[] args) {
Map<String, String> dict = new HashMap<String, String>();
...
for eachMapEntry(String k, String v : dict) {
System.out.println(k + ": " + v);
}
}
