In this tutorial, we will see “How to find Missing Number in an Array using Java 8 Streams?”
Find missing number in an array in java 8 using streams
Java 8 – How to find missing number in an array using Streams? Share on X
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | /** * Using Java 8, Find the missing number in an array * @author Deepak Verma * */ import java.util.Arrays; public class Find_Missing_Number_In_Array_Java8Stream_Example { public static void main(String args[]) { int[] arrayOfIntegers = {1, 2, 3, 4, 6, 7, 8, 9}; int maxValue = Arrays.stream(arrayOfIntegers).max().getAsInt(); int expectedSum = maxValue * (maxValue + 1) / 2; int actualSum = Arrays.stream(arrayOfIntegers).sum(); int missingNumber = expectedSum - actualSum; System.out.println("Missing number in the array is: " + missingNumber); } } |
Output:
1 | Missing number in the array is: 5 |
Find missing number in an array in java 8 using streams
In the above code, we use the Java 8 stream
API and along with that, the max
and sum
methods to find the missing number in the provided array. The variable denotes by expectedSum
holds the sum of all numbers from 1 to the maximum value in the given array. While on the other hand, the variables denotes by actualSum
holds the sum of all numbers in the array. At last, the missing number is figured out by subtracting the actual sum value from the expected sum value.
Find missing number in an array in java 8 using streams
Java 8 – How to find missing number in an array using Streams? Share on X
Do you like this Post? – then check my other helpful posts:
- Convert a Stream to a List in Java 8
- Stream maptoint in Java 8 with examples
- Double the numbers of specified ArrayList using Streams
- Double the even / odd numbers of a specified ArrayList using Streams
- How to check if Number is Prime or not using Streams
- Retrieve Even/Odd Numbers within the Range using Java 8 Streams
- How to add/sum up the ArrayList integers using Java8 Streams
- Generate Prime Numbers in Java 8 using Streams
- Comparator example – Collections sort with/without Lambda in Java 8
- How to pass function as a parameter in a method in Java 8?
- Remove duplicates from ArrayList in Java 8
- ForEach examples for Map/List in Java 8
Other Useful References:
Very helpful content
Glad you find it helpful. Thank you.