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

将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.

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

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器