Reputation: 13
I am trying to print duplicate elements in one d array using for each
loop. But my output was an unexpected one. Could anyone please assist?
package Login;
public class DupsArray {
static int[] a = {1,2,3,3};
public static void main(String[] args) {
int length = a.length;
for(int i=0;i<=length-1;i++) {
for(int j : a) {
for(j=1;j<=length-1;j++) {
if(a[i]==(a[j]) ) {
System.out.println("Found duplicate");
} else {
System.out.println("No duplicates found");
}
}
}
}
}
The results show as follows:
The expected results to be print duplicate found.
Upvotes: 1
Views: 5154
Reputation: 673
You can use Sets like that :
Integer[] a = {1, 2, 3, 3, 5, 5, 7, 8, 7};
Set<Integer> duplicatesSet = new HashSet<>();
Set<Integer> helperSet = new HashSet<>();
for (Integer element : a) {
if (!helperSet.add(element)) { // NOTE*
System.out.println("Duplicate found : " + element);
duplicatesSet.add(element);
}
}
Then you can do whatever you like with the duplicates set
for(Integer el : duplicatesSet){
System.out.println(el);
}
Note*
According to javadocs :
boolean add(E e);
Adds the specified element to this set if it is not already present
return true if this set did not already contain the specified element
This way we can know if the element is already in the set, if it is we can add it to our duplicates.
Upvotes: 0
Reputation: 2014
try this and update as per your requirement
public class Main{
public static void main(String[] args) {
int[] ar = new int[] {1, 1, 3, 3, 4, 5, 7, 8};
int size = ar.length;
int error = 0;
for(int i = 0; i < size; i++){
for(int j = i+1; j < size; j++){
if(ar[i] == ar[j]){
if(i != j){
error = error + 1;
System.out.println("dulicate element " + j);
}
}
}
}
System.out.println("total number of duplicate element " + error);
}
}
Upvotes: 0
Reputation: 347
We can do something like this
Integer[] arr = {1, 2, 3, 3, 5, 5, 7, 8, 7};
Set<Integer> set = new HashSet<Integer>();
for (Integer i : arr) {
if (set.add(i) == false)
{
System.out.println(i);
}
}
Upvotes: 1
Reputation: 73
Try using the below logic which compares every element with all other element in the array, if any duplicate is found,it stops the execution to continue futher
for(int i = 0; i < a.length;i++) {
for (int j = i + 1 ; j < a.length; j++) {
if (a[i] == a[j]) {
System.out.println("Found duplicate");
return;
}
}
}
System.out.println("No duplicate Found");
Upvotes: 1