suze suze - 3 months ago 14
Java Question

Simple program for removing Duplicate elements in Java using list

I'm a beginner,I tried to find duplicate elements in the given list but for some reason I'm getting the element 3 printed twice. Can anyone help me out?

OUTPUT:


1 1 2 2 3 3 3 3 3 3 3 4 4 4 5 5 6 6


Duplicate element(s)


1 2 3 3 3 3 4 5 6


3 4

Duplicate element(s) removed

1 2 3 3 4 5 6

public class Duplicate {
public static void main(String[] args) {
int[] array={1,2,2,3,3,4,5,5,3,4,3,4,6,6,1,3,3,3};
Arrays.sort(array);
List<Integer> list=new ArrayList<Integer>();
for(int x:array)
list.add(x);
for(int i=0;i<list.size();i++)
System.out.print(list.get(i)+" ");
System.out.println("\nDuplicate element(s)");
for(int i=0;i<list.size();i++){
for(int j=i+1;j<list.size();j++){
if((list.get(i)==list.get(j))){
System.out.print(list.get(j)+" ");
list.remove(j);
}
}
}
System.out.println();
for(int i=0;i<list.size();i++){
for(int j=i+1;j<list.size();j++){
if((list.get(i)==list.get(j))){
System.out.print(list.get(j)+" ");
list.remove(j);
}
}
}
System.out.println("\nDuplicate element(s) removed");
for(int i=0;i<list.size();i++)
System.out.print(list.get(i)+" ");
}
}

Answer

Try with this:

public static void main(String[] args) {

    int[] array = {1, 2, 2, 3, 3, 4, 5, 5, 3, 4, 3, 4, 6, 6, 1, 3, 3, 3};
    Arrays.sort(array);
    List<Integer> list = new ArrayList<>();
    for (int x : array) {
        list.add(x);
    }
    for (int i = 0; i < list.size(); i++) {
        System.out.print(list.get(i) + " ");
    }
    System.out.println();
    System.out.println("\nDuplicate element(s)");
    Integer last = null;
    Iterator<Integer> it = list.iterator();
    while (it.hasNext()){
        Integer n = it.next();
        if (n.equals(last)){
            System.out.print(n + " ");
            it.remove();
        }
        last = n;
    }
    System.out.println();

    System.out.println("\nDuplicate element(s) removed");

    for (int i = 0; i < list.size(); i++) {
        System.out.print(list.get(i) + " ");
    }
    System.out.println();
}