How can I use an IntStream to sum specific indexed numbers of an int array?
While you can solve this task by sorting, as shown in other answers, this is unnecessary work. “Summing four out of five” values means “summing all but one”, so all you have to do, is to subtract one element from the sum of all elements. Subtract the maximum element to get the minimum sum of four, subtract the minimum element to get the maximum sum of four:
IntSummaryStatistics s = IntStream.of(1, 3, 5, 7, 9).summaryStatistics();
System.out.printf("%d %d%n", s.getSum()-s.getMax(), s.getSum()-s.getMin());
16 24
Or, if the source is an array:
IntSummaryStatistics s = Arrays.stream(array).summaryStatistics();
System.out.printf("%d %d%n", s.getSum()-s.getMax(), s.getSum()-s.getMin());
You might just be looking for something like Intstream.range(int startInclusive, int endExclusive)
Returns a sequential ordered IntStream from
startInclusive
(inclusive) toendExclusive
(exclusive) by an incremental step of 1.
Over these then you can perform either sum
directly or use IntSummaryStatistics
with summaryStatistics()
to further access the count, average, max, min etc.
Edit2: If you're looking forward to get the sum as long
use summaryStatistics().getSum()
Edit2: If you're specifically looking to access the statistics of the data of an array, you can use Arrays.stream(int[] array, int startInclusive, int endExclusive)
which would return back an Instream
as well.