4

Is there an (elegant) way to define a min/max lambda expression?

public class MathFunction{
  private java.util.function.Function <double[], Double> function = null; 
  public MathFunction ( Function <double[], Double> pFunction ){    
     this.function = pFunction;   
  }
}
// now defining a min-function...
MathFunction func = new MathFunction((x) -> min(x));

Of course min(x) does not work. I need a way to sort an array "on the fly".

1
  • Probable duplicate: related question Commented Nov 13, 2015 at 16:00

1 Answer 1

4

You could stream the array and extract the min from it:

MathFunction func = 
    new MathFunction((x) -> Arrays.stream(x).min().getAsDouble());
Sign up to request clarification or add additional context in comments.

5 Comments

Perfect!! I've already tried Arrays.stream but did not know about that .getAsDouble(). Thank you very much.
@user1511417 - There's also Arrays.stream(x).summaryStatistics() from which you can pull getMin() and getMax() and so only traversing the ayrray once.
@OldCurmudgeon cool, didn't know about that. Note that you'd be performing five calculations for each item in the array instead of just one that min does. For large arrays this may be a noticeable difference.
@Mureinik - min would still have to perform a complete pass of the array. If you need both min and max (as OP seems to) the this trick would ensure one pass and deliver both at once.
@OldCurmudgeon agreed - if you need multiple answers, it's best to traverse the list only once. If you only need min, though, it's a shame to have to calculate a bunch of other things.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.