Does Java 8 provide a good way to repeat a value or function?

后端 未结 5 1032
遥遥无期
遥遥无期 2020-12-02 05:26

In many other languages, eg. Haskell, it is easy to repeat a value or function multiple times, eg. to get a list of 8 copies of the value 1:

take 8 (repeat 1         


        
5条回答
  •  甜味超标
    2020-12-02 05:58

    This is my solution to implementing the times function. I'm a junior so I admit it could be not ideal, I'd be glad to hear if this is not a good idea for whatever reason.

    public static  R times(int count, Function f, T t) {
        while (count > 0) {
            f.apply(t);
            count--;
        }
        return null;
    }
    

    Here's some example usage:

    Function greet = greeting -> {
        System.out.println(greeting);
        return null;
    };
    
    times(3, greet, "Hello World!");
    

提交回复
热议问题