Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define and invoke inline a lambda expression in Java

Tags:

lambda

java-8

I'd like to do something like this:

{ param -> if ( <condition over param> ) process ( param ) } ( provider () );

i.e., param is a value returned by a method (which, let's say, takes a long time to run, so I want to invoke it once only) and I want to pass on such value only if it fulfils a condition.

The alternative would be:

Param param = provider(); if ( <cond> ) process ( param );

But the lambda-based version, if I could make it working, would be shorter. The code above doesn't compile in Java and I cannot figure out if what I'm thinking about is possible and how.

like image 739
zakmck Avatar asked Sep 08 '26 13:09

zakmck


2 Answers

Well, you can do something like

                                        // use Type::process for a static method
Stream.of(provider()).filter( «cond» ).forEach(this::process);

though there is really no benefit over an ordinary imperative statement here

If you want to limit the scope of the newly introduced variable, you can create a block.

{ Param param = provider(); if( «cond» ) process(param); }

and, as a side note, debugging will be much easier with this conventional construct.

like image 182
Holger Avatar answered Sep 11 '26 08:09

Holger


Thanks all for your replies. I've found an approach similar to what @Holger suggests:

Optional.of ( provider() ).map ( v -> { if ( <cond> ) process ( v ); return null; } )

(return only needed if process() returns void). I agree it's quicker to define an intermediate variable and probably I'll end up to do so. Yet, there must be some psychological reasons why I'm attracted more to functional forms like the above. When they're many, they seem quicker to write, maybe because you don't need to think of new variable names (you need multiple variable definitions if there are different types involved).

like image 21
zakmck Avatar answered Sep 11 '26 08:09

zakmck



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!