10 July, 2019

Find one missing number from a list of numbers

In this article, we will find the missing number from a list of numbers using java 8.  This is one of important questions asked in interview. This program is to find the only one missing number. Check how to find all missing numbers from a list. In this program we will use only java 8 stream to find the missing number. Earlier post we had seen how to use stream to sort the employee. Check more how find one missing number using traditional core java style


FindMissingNumber.java

package com.javadevelopersguide.lab.basic;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.stream.IntStream;
/**
 * This program finds the missing number from a list. This is only for one
 * missing number. Used the java 8 for this program.
 *
 * @author manoj.bardhan
 *
 */
public class FindMissingNumber {
public static void main(String[] args) {
ArrayList<Integer> numberList = new ArrayList<Integer>(Arrays.asList(1, 3, 2, 4, 5, 6, 7, 9, 10));
// Get the Max value from the List.
int maxValue = numberList.stream().max(Comparator.naturalOrder()).get().intValue();
// Get sum of all natural numbers - upto the above maxvalue
int sumOfAllNumber = IntStream.range(1, maxValue + 1).sum();
// Get the sum of all number inside List.
int sumofList = numberList.stream().mapToInt(Integer::intValue).sum();
// Now print the missing number.
System.out.println("The Missing Number is:: " + (sumOfAllNumber - sumofList));
}
}



Output - 

The Missing Number is:: 8




Happy Learning.



Follow for more details on @Facebook!!!

Find More  :-

5 comments:

  1. Thanks for sharing such an article. As a JAVA training institute ACL IT academy encourage such articles. We will surely note this article and will share with our candidates. Thanks and regards
    ACL IT academy- Java Training Institute in Kolkata

    ReplyDelete
  2. I want to thank you for this good read!! I definitely enjoyed every little bit of it. I've got you book-marked to look at new stuff you post…
    Java Training in Bangalore
    Advanced Java Training in Bangalore

    ReplyDelete
  3. Good Post! Thank you so much for sharing the post, it was so good to read and useful to improve
    Java Training in Electronic City

    ReplyDelete