Check duplicated value in array - LearnHowToCode SarkariResult.com Interview Questions and Answers LearnHowToCodeOnline

Check duplicated value in array

Here i attached a java example to show how to check duplicated value in an array. I show two methods to implement this.
1) Using two for loop to compare each values in array – Line 21
2)Using HashSet to detect duplicated value. – Line 40
Hope help, if you know any other method to compare duplicated value in array, please share it to me.
 

package com.mycareerrepublic;

import java.util.Set;
import java.util.HashSet;

public class CheckDuplicate
{
public static void main(String args[])
{
String [] sValue = new String[]{"a","b","c","d","","","e","a"};

if(checkDuplicated_withNormal(sValue))
System.out.println("Check Normal : Value duplicated! \n");
if(checkDuplicated_withSet(sValue))
System.out.println("Check Set : Value duplicated! \n");

}

//check duplicated value
private static boolean checkDuplicated_withNormal(String[] sValueTemp)
{
for (int i = 0; i < sValueTemp.length; i++) {
String sValueToCheck = sValueTemp[i];
if(sValueToCheck==null || sValueToCheck.equals(""))continue; //empty ignore
for (int j = 0; j < sValueTemp.length; j++) {
if(i==j)continue; //same line ignore
String sValueToCompare = sValueTemp[j];
if (sValueToCheck.equals(sValueToCompare)){
return true;
}
}

}
return false;

}

//check duplicated value
private static boolean checkDuplicated_withSet(String[] sValueTemp)
{
Set sValueSet = new HashSet();
for(String tempValueSet : sValueTemp)
{
if (sValueSet.contains(tempValueSet))
return true;
else
if(!tempValueSet.equals(""))
sValueSet.add(tempValueSet);
}
return false;
}


}


About Mariano

I'm Ethan Mariano a software engineer by profession and reader/writter by passion.I have good understanding and knowledge of AngularJS, Database, javascript, web development, digital marketing and exploring other technologies related to Software development.

0 comments:

Featured post

Political Full Forms List

Acronym Full Form MLA Member of Legislative Assembly RSS Really Simple Syndication, Rashtriya Swayamsevak Sangh UNESCO United Nations E...

Powered by Blogger.