Find only duplicate number in given list in java


In this core java programming tutorial we will write a program to Find only duplicate number in given list in java.



Hi! In this post we will write a program to find out only duplicate number in given list in java.

We are given a list from 1 to 10(where series go from 1 to 10), with one added duplicate number in list.
Note: in below program as program suggests there must not be more than 1 duplicate number,
in below program we could change 10 to any other number as well.

Example>
Let’s say series given to us is : 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 5
We got to figure out 5 (as it is duplicate).


Full Program/SourceCode / Example to Find only duplicate number in given list in java >
/** Copyright (c), AnkitMittal www.JavaMadeSoEasy.com */
import java.util.ArrayList;
import java.util.List;
public class FindOnlyDuplicateNumberInListExample {
  
   public static void main(String...a){
       List<Integer> list = new ArrayList<Integer>();
       int highestNumberInList=10;   //you may change it in future.
       for(int i=1;i<=highestNumberInList;i++){
           list.add(i);
       }
       list.add(5); //add duplicate number in list(please ensure you don't add more than one duplicate number in list)
       System.out.println("list is: "+list);
       System.out.println("Only duplicate number in list is: "+findOnlyDuplicateNumberInList(list,highestNumberInList));
   }
   /**
   * returns only duplicate number in list.
   */
   public static int findOnlyDuplicateNumberInList(List<Integer> list, int highestNumberInList){
    
       int sumOfNumbersList = 0;
       for(int n:list){
          sumOfNumbersList =sumOfNumbersList+n;
       }
      
       int onlyDuplicateNumberInList = sumOfNumbersList - ((highestNumberInList)*(highestNumberInList+1)/2);
       return onlyDuplicateNumberInList;
   }
}
/*OUTPUT
list is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 5]
Only duplicate number in list is: 5
*/


So in this core java programming tutorial we wrote a program to Find only duplicate number in given list in java.


Previous program                                                                  Next program




Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.




RELATED LINKS>










No comments:

Post a Comment