There is a function in PHP like this
function array_walk(array &$array, callable $callback, $userdata = null): bool {}
I want to use this method in Java. Can anyone help me?
For example, I want to convert this function to Java
array_walk($result, function (&$value, $key) {
$value = sprintf('%s/%s', $key, $value);
});
I have searched out what does this method do at W3C and I can clearly say that for this purpose the Java 8 Stream API takes the place using the forEach()
:
String[] a = {"blue", "red"};
Stream.of(a).forEach(i -> System.out.println("This is a " + i + " color."));
Results in:
This is a blue color.
This is a red color.
You can also implement your one which does exactly you want using @FunctionalInterface. However you cannnot use it since you are stucked in Java 7 and earlier. In this case you have to use the ordinary for-loop
or the very own class and @Override
the implementation:
public class ArrayWalker<T> {
T[] t;
public ArrayWalker(T[] t) {
this.t = t;
}
public void function(T t) {}
public ArrayWalker<T> walk() {
for (int i=0; i<t.length; i++) {
function(t[i]);
}
return this;
}
}
Usage:
new ArrayWalker<String>(array) {
@Override
public void function(String str) {
System.out.println("This is a " + str + " color.");
}
}.walk();
It will result in the same output as the example above.