Find duplicate elements and remove it.
This is a java example for finding duplicate elements using for loop and remove
the duplicate in given array. Here it is shows how we can do it two different ways.
In class we have use Hashset . Code is simple only two java class is loose coupled.
import java.util.HashSet;
public class RemoveDuplicatsinArray {
public void RemoveDublicatesA() {
String[] strArray
= {"JAVA", "Python", "Perl", "JAVA", "C",
"CPP", };
for (int
i = 0; i < strArray.length-1; i++)
{
for
(int j = i+1; j < strArray.length; j++)
{
if(
(strArray[i].equals(strArray[j])) && (i != j) )
{
System.out.println("Duplicate
Element is : "+strArray[j]);
}
}
}
}
public static
void main(String[]
args) {
System.out.println("===== Using
For loop===========================");
RemoveDuplicatsinArray
a= new RemoveDuplicatsinArray();
a.RemoveDublicatesA();
System.out.println("===== Using
HashSet ===========================");
System.out.println("****Remove
Duplicats using Collection:*********");
DuplicatesInArray b=new DuplicatesInArray();
b.RemoveDublicatesB();
}
}
class DuplicatesInArray
{
public void
RemoveDublicatesB()
{
String[] strArray
= {"JAVA", "Python", "Perl", "JAVA", "C",
"CPP" ,"CPP"};
HashSet
set = new HashSet ();
for (String
arrayElement : strArray)
{
if(!set.add(arrayElement))
{
System.out.println("Duplicate
Element is : "+arrayElement);
}
}
System.out.println(
" Arrays Elecments ");
for (String
arrayElement : strArray)
{
System.out.println(
arrayElement);
set.add(arrayElement);
}
System.out.println("Elements
After removing Dublicates:" );
for(String
arryset:set){
System.out.println(
arryset);
}
}
}
===== Using For loop===========================
Duplicate Element is : JAVA
===== Using HashSet ===========================
****Remove Duplicats using Collection:*********
Duplicate Element is : JAVA
Duplicate Element is : CPP
Arrays Elecments
JAVA
Python
Perl
JAVA
C
CPP
CPP
Elements After removing Dublicates:
JAVA
CPP
C
Perl
Python
Find duplicate elements and remove it.
Reviewed by Mukesh Jha
on
1:54 AM
Rating:
No comments:
Add your comment