Java 8: Lambda with variable arguments

前端 未结 6 1806
天命终不由人
天命终不由人 2021-01-04 02:27

I am looking for a way to invoke multiple argument methods but using a lambda construct. In the documentation it is said that lambda is only usable

6条回答
  •  [愿得一人]
    2021-01-04 02:40

    What I did was for my own use case was to define a helper method that accepts varargs and then invokes the lambda. My goals were to 1) be able to define a function within a method for succinctness and scoping (i.e., the lambda) and 2) make calls to that lambda very succinct. The original poster may have had similar goals since he mentioned, in one of the comments above, wanting to avoid the verbosity of writing Object[] {...} for every call. Perhaps this will be useful for others.

    Step #1: define the helper method:

    public static void accept(Consumer invokeMe, Object... args) {
        invokeMe.accept(args);
    }
    

    Step #2: define a lambda which can use a varying number of arguments:

    Consumer add = args -> {
        int sum = 0;
        for (Object arg : args)
            sum += (int) arg;
        System.out.println(sum);
    };
    

    Step #3: invoke the lambda many times - this succinctness was why I wanted the syntactic sugar:

    accept(add, 1);
    accept(add, 1, 2);
    accept(add, 1, 2, 3);
    accept(add, 1, 2, 3, 4);
    accept(add, 1, 2, 3, 4, 5);
    accept(add, 1, 2, 3, 4, 5, 6);
    

提交回复
热议问题