title: How can I use an IntStream to sum specific indexed numbers of an int array?
body: <p>I've been studying Kotlin and Java with lambdas. I'm trying the use the most of functional programming that I can, even though I don't know much of functional programming.</p>
  
  <p>I'm using HackerRank's problems to study (and Koans to study Kotlin as well). I'm currently solving the problems using both Kotlin and Java 8.</p>
  
  <p>I'm trying to solve the <a href="https://www.hackerrank.com/challenges/mini-max-sum/" rel="nofollow noreferrer">MiniMax-Sum problem</a>. Basically, the description is something like this:</p>
  
  <blockquote>
    <p>Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers.</p>
  </blockquote>
  
  <p>I'm trying to use the most of the streams API that I can when in Java. The simple question is: how can I reduce, after sorting, the int array to its four first elements (and last, in a different scenario) and sum its values? I was trying to use <code>IntStream</code>, but it seems that it's very difficult without using <code>List</code>. I was wondering if it possible to use directly the <strong><code>int[]</code> array with <code>IntStream</code></strong> to sort and reduce the elements and them sum it.</p>
  
  <p>Using Kotlin I solved like this:</p>
  
  <pre><code>val minSum: Long = arr.sortedArray().copyOfRange(0, 4).sum().toLong()
  val maxSum: Long = arr.sortedArray().copyOfRange(1, 5).sum().toLong()
  println("$minSum $maxSum")
  </code></pre>
  
  <p>I'm trying to use the <code>range</code> method, together with <code>sorted</code> and <code>sum</code>. It works. The problem is that the sum always returns an <code>int</code>, and sometimes the sum is a <code>long</code> value. Here's my code:</p>
  
  <pre><code>long min = IntStream.range(0, arr.length)
          .sorted()
          .sum();
  
  long max = IntStream.range(1, arr.length + 1)
          .sorted()
          .sum();
  </code></pre>
  
  <p>Result is 10 (min) and 15 (max) for the input <code>new long[] {256741038, 623958417, 467905213, 714532089, 938071625}</code></p>
  
  <hr>
  
  <p>Thanks a lot to everyone that took the time to help! Guess I did not see the <code>LongStream.of</code> method :D I solved using 2 different ways (pointed by @Aomine, @nullpointer and @Holger):</p>
  
  <pre><code>// using Arrays and Stream
  Arrays.sort(arr);
  long min = Arrays.stream(arr, 0, 4).sum();
  long max = Arrays.stream(arr, 1, 5).sum();
  
  System.out.println(min + " " + max);
  
  // and using LongSummaryStatistics (thanks @Holger)
  LongSummaryStatistics ls = LongStream.of(arr).summaryStatistics();
  System.out.println((ls.getSum() - ls.getMax()) + " " + (ls.getSum() - ls.getMin()));
  </code></pre>
  
  <p>Thanks a lot guys!</p>