Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoke a method from a lambda-function's result

Tags:

java

lambda

I have an object (Adult) with another object (Child) as a parameter. I am trying to write a Function that will return the child's name if given the adult.

I wrote this:

public static void main(String[] args) {
    Function<Adult, Object> adult_name_f = Adult::getName;
    Function<Adult, Object> adult_child_f = Adult::getChild;
    Function<Adult, Object> child_name_f = Adult::getChild.getName;
}

static class Adult {
    String name;
    Child child;

    public Child getChild() {
        return child;
    }

    public String getName() {
        return name;
    }
}

static class Child {
    String name;

    public String getName() {
        return name;
    }
}

but (obviously) Adult::getChild.getName is not a valid Function.

Is there a way to return the name of the child if given the adult?

like image 762
ryvantage Avatar asked Apr 29 '26 09:04

ryvantage


1 Answers

First, you should specify the appropriate return type of the Function.

Function<Adult, String> adult_name_f = Adult::getName;
Function<Adult, Child> adult_child_f = Adult::getChild;

You can then use the Function.andThen() method to create the third Function.

Function<Adult, String> child_name_f = adult_child_f.andThen(Child::getName);

Alternatively, and more commonly done, to make a method chain, you can define the Function using a lambda expression. You can even use lambda expressions for the first two, but method reference is better (less generated code).

Function<Adult, String> adult_name_f = a -> a.getName();
Function<Adult, Child> adult_child_f = a -> a.getChild();
Function<Adult, String> child_name_f = a -> a.getChild().getName();

Test

Adult mary = new Adult("Mary", new Child("Jesus"));
System.out.println(adult_name_f.apply(mary));  // prints: Mary
System.out.println(adult_child_f.apply(mary)); // prints: Test$Child@XXXXXXXX
System.out.println(child_name_f.apply(mary));  // prints: Jesus
like image 100
Andreas Avatar answered May 01 '26 21:05

Andreas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!