-5

I have an Arraylist, which contains employee class objects. each employee class object contains different employee records (also duplicates).employee class contains emp id and name.Based on employee id want to find duplicates.

I want to find the duplicate records and store it in a separate arraylist and delete those duplicates from original arraylist.

  • Emp class contains Emp Id and Name..based on emp id I want to find duplicate records. – Java Learner Jun 24 '17 at 15:28
  • thanks james for your suggestion..I have edited my question. – Java Learner Jun 24 '17 at 15:39
  • 2
    It looks to me like you haven't even made any effort at solving this for yourself. Please take some time, try it for yourself, and if you are having problems, you can come back with a more specific question. – Joe C Jun 24 '17 at 16:21

1 Answers1

0

I suppose you have a Employee class like this:

class Employee {
      public Integer id;
      public String name;

      public Employe(Integer id, String name) {
             this.id = id;
             this.name = name;
      }
}

You can split the problem in three parts:

  1. Order the arraylist by id using method sort of Collections
  2. Remove the duplicate from original arraylist
  3. Add the duplicate into duplicates arraylist

Of course, you have to use Comparator for ordering elements.

Example of implementation:

 import java.util.*;

 public class Test {
    public static void main(String[] args) {
            List<Employee> original = new ArrayList<Employee>();
            List<Employee> duplicates = new ArrayList<Employee>();

            original.add(new Employee(1,"Test 1"));
            original.add(new Employee(2,"Test 2"));
            original.add(new Employee(3,"Test 3"));
            original.add(new Employee(1,"Test 4"));
            original.add(new Employee(2,"Test 2"));

            Collections.sort(original, new Comparator<Employee>() {
                    @Override
                    public int compare(Employee e1, Employee e2)
                    {
                            return  e1.id.compareTo(e2.id);
                    }
            });

            for(int i=1;i<original.size();i++) {
                    if(original.get(i-1).id.equals(original.get(i).id)) {
                            duplicates.add(original.get(i));
                            original.remove(i);
                            i = i -1;
                    }
            }
      }
 }
cirosomma
  • 71
  • 7