Master Mind Master Mind - 1 year ago 113
Java Question

Java stream : first element of the stream minus the sum of the rest of the stream

I have an array of integer for example:

{ 30 , 2, 3, 4, 5}

Is it possible to create a lambda expression (using streams) for making the difference between the first element of the array ( in our example 30) and the sum of the rest of array
(2+3+4+5 = 13)
so the result would be 17?

Answer Source

You could calculate the sum of the last n-1 elements of the array and subtract it from the first element :

int result = inputArray[0] - IntStream.of(inputArray).skip(1).sum();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download