Can a java lambda have more than 1 parameter?

后端 未结 6 2066
渐次进展
渐次进展 2020-11-28 18:24

In Java, is it possible to have a lambda accept multiple different types?

I.e: Single variable works:

    Function  adder = i         


        
6条回答
  •  旧巷少年郎
    2020-11-28 18:57

    Another alternative, not sure if this applies to your particular problem but to some it may be applicable is to use UnaryOperator in java.util.function library. where it returns same type you specify, so you put all your variables in one class and is it as a parameter:

    public class FunctionsLibraryUse {
    
        public static void main(String[] args){
            UnaryOperator personsBirthday = (p) ->{
                System.out.println("it's " + p.getName() + " birthday!");
                p.setAge(p.getAge() + 1);
                return p;
            };
            People mel = new People();
            mel.setName("mel");
            mel.setAge(27);
            mel = personsBirthday.apply(mel);
            System.out.println("he is now : " + mel.getAge());
    
        }
    }
    class People{
        private String name;
        private int age;
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }
    }
    

    So the class you have, in this case Person, can have numerous instance variables and won't have to change the parameter of your lambda expression.

    For those interested, I've written notes on how to use java.util.function library: http://sysdotoutdotprint.com/index.php/2017/04/28/java-util-function-library/

提交回复
热议问题