-2

As we know , Java 8 supports functional programming.

We can pass method as a parameter and return a method from another method.

I know , call back is one of the real time usecase for passing method as parameter . But I couldn't find any real usecase for returning method from another method . Please give me some real time example for this.

JavaUser
  • 25,542
  • 46
  • 113
  • 139

2 Answers2

1

There are plenty of examples of taking/returning functional interfaces in the JDK itself.

Here are some use cases that are obvious:

"Standard" logic:

Function.identity() //standard implementation for obj -> obj

Logic chaining (function composition):

Function<String, String> upperCase = String::toUpperCase;
Function<String, String> upperCaseAndTrim = upperCase.andThen(String::trim);

andThen is a composition of functions, and it's only logical to return a functional interface.

And a related use case:

ToIntFunction<String> intExtractor = String::length;
Comparator<String> stringLengthComparator = Comparator.comparingInt(intExtractor);

Here, a standard int comparator is created by Comparator, taking a function that knows how to produce an int from the collection element type.

This is probably another case of composed functions:

Predicate<String> isValid = s -> s.length() <= 10;
Predicate<String> isInvalid = isValid.negate();

negate() reverses the logic implemented by the original method.

ernest_k
  • 44,416
  • 5
  • 53
  • 99
1

The 'methods' you talk about are called lambdas and they are a powerful tool, because they are more than they initially seem. On the first look a lambda is nothing but behavior wrapped in slim syntax. But actually a lambda can do much more.

For example, lambdas 'capture' values they use from their respective scope at creation time:

...
final MyType t = someObject;
Runnable runner = () -> t.someMethod();
return runner;
...

...
runner.run();

This is actually a call to the someMethod of the object someObject. This means, that a lambda actually has a context at the position it is created, as opposed to where it is called.

But there is more: You can actually pass just a method (as you describe), if the method fits the specific signature of the expected interface:

List<String> myStrings = ...;
myStrings.forEach(System.out::println);

As you can see, you can actually link object-specific methods, not just static ones. Once again, you have passed context.

Now to the specific question: Why return a method-lambda from a method call?

Map<String, Consumer<String>> handlers = new HashMap<>();
...

public Consumer<String> getHandler(String key) {
    Consumer<String> h = handlers.get(key);
    if (h == null) {
        return System.out::println;
    }
    return h;
}

Now you can link the handler you store somewhere central to another object, for which you define a behavior.

TreffnonX
  • 2,924
  • 15
  • 23