educative.io

Benefit of Unary Operator

Regarding the below code, why don’t we use Person person = new Person("John", 34);? What is the benefit of unary operator here?

    public static void main(String args[]) {
        Person person = new Person();
        UnaryOperator<Person> operator = (p) -> {
            p.name = "John";
            p.age = 34;
            return p;
        };

        operator.apply(person);
        System.out.println("Person Name: " + person.getName() + " Person Age: " + person.getAge());
    }

Course: Educative: Interactive Courses for Software Developers
Lesson: Educative: Interactive Courses for Software Developers

In the provided code, the UnaryOperator<Person> is used to modify the state of the existing object (i.e., person) by changing its name and age rather than creating a new Person object with a different name and age.

If we use Person person = new Person("John", 34);, a new Person object will be created with the name “John” and age 34, but this will not modify the state of any existing object.

On the other hand, using the UnaryOperator<Person> interface, the lambda expression (p) -> { p.name = "John"; p.age = 34; return p; }; is applied to the existing Person object passed as an argument to the apply() method. This modifies the state of the existing Person object, which is accommodative if we need to update the state of an existing object instead of creating a new object.

Recap: The benefit of using the unary operator here is to modify the state of an existing object (i.e., person) rather than creating a new Person object with a different state.

Happy learning at Educative.

1 Like