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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With