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

后端 未结 5 1031
遥遥无期
遥遥无期 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:56

    Once a repeat function is somewhere defined as

    public static BiConsumer repeat = (n, f) -> {
        for (int i = 1; i <= n; i++)
            f.run();
    };
    

    You can use it now and then this way, e.g.:

    repeat.accept(8, () -> System.out.println("Yes"));
    

    To get and equivalent to Haskell's

    take 8 (repeat 1)
    

    You could write

    StringBuilder s = new StringBuilder();
    repeat.accept(8, () -> s.append("1"));
    

提交回复
热议问题