dongwei4444 2017-09-26 11:36
浏览 84
已采纳

将array_walk从php转换为java方法

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);
});
  • 写回答

1条回答 默认 最新

  • dongyou8087 2017-09-26 11:54
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?