Java 8: Lambda with variable arguments

前端 未结 6 1817
天命终不由人
天命终不由人 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:44

    I was curious if a lambda for a variable number of arguments would work. Indeed it seems to. See:

    public class Example {
        public interface Action {
            public void accept(T... ts);
        }
    
        public static void main(String args[]) {
            // Action a = (String... x) -> { also works
            Action a = (x) -> {
                for(String s : x) {
                    System.out.println(s);
                }
            };
    
            a.accept("Hello", "World");
        }
    }
    

    I know the question has been answered. This is mainly for others who are curious and come across this post.

提交回复
热议问题