0

Double::sum is a method reference for adding doubles, ie. (a,b) -> a+b.

Why is there not a method reference for minus in the JDK? I.e. (a,b) -> a-b?

Graeme Moss
  • 7,995
  • 4
  • 29
  • 42
  • 2
    Using a library for this is counter-productive, you already spent more time writing this question than the code you already know works and is simple enough. – Tunaki Sep 21 '15 at 10:14
  • https://functionaljava.googlecode.com/svn/artifacts/3.0/javadoc/fj/function/Integers.html though not used myself – Joop Eggen Sep 21 '15 at 10:28
  • 4
    `Double::sum` is a handy method reference for reduction operations and similar. Since minus is not associative, it’s not appropriate for such operations. However, if you need a minus, just use `(a,b)->a-b`. Adding a 3rd library dependency for that sounds insane. – Holger Sep 21 '15 at 10:30
  • Ouch. Some harsh criticisms of the question here! In my case, I need to supply a ToDoubleBiFunction and I could see that Double::sum was available, but not Double::minus, and I wondered why. Also, I personally find Double::sum more readable than (a,b) -> a+b (and Double::+ or just + would be even better) but that's perhaps personal style. – Graeme Moss Sep 21 '15 at 11:31
  • @Holger I'll mark your answer correct if you mention the difference between Double::sum and Double::minus. Thanks. – Graeme Moss Sep 21 '15 at 11:37

4 Answers4

9

The primary purpose of methods like Double.sum is to aid use cases like reduction or Arrays.parallelPrefix Since minus is not an associative function, it is not appropriate for this use case.

Adding 3rd party library dependencies just for the sake of such a simple method, is not recommended. Keep in mind, that you always can create your own method, if you prefer named methods over lambda expressions.

E.g.

static double minus(double a, double b) {
    return a-b;
}

and using MyClass::minus is as informative as ThirdPartyClass::minus

Holger
  • 285,553
  • 42
  • 434
  • 765
2

There is no inbuilt method. But I don't think, itdo any other magic than simply doing

double result = a-b;

It seems you are over thinking here :)

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

As such there is no inbuilt method which is used to subtract the doubles. However if you are using BigDecimal to store the decimals then you can try this:

BigDecimal a = new BigDecimal("10.6");
BigDecimal b = new BigDecimal("4.3");
BigDecimal result = a.subtract(b);
System.out.println(result); 

else you can use the simple way of subtracting two numbers ie, a-b. Also to note that in Java, double values are IEEE floating point numbers

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331