1

suppose i have to add 3 student objects to array list in java. having some attributes.Attributes are name,id,age. Before inserting into array list i have to check uniqueness on name attribute.or u can say i have to remove duplicate names.can anybody suggest how to write the code to remove these duplicate attributes?

    List<Student> list=new Array List<Student>();
    list.add(new Student(21,"x",25));
    list.add(new Student(21,"y",26));
    list.add(new Student(22,"x",27));

6 Answers6

2

Make sure Student overrides equals() to test for how you consider Students to be equivalent and then:

if (!list.contains(someStudent)) {
    list.add(someStudent);
} else {
    System.out.println("Duplicate student.");
}
indivisible
  • 4,892
  • 4
  • 31
  • 50
  • 4
    As mentioned in the accepted answer [here](http://stackoverflow.com/questions/27581/overriding-equals-and-hashcode-in-java), it is good practice to also override `hashCode` when `equals` is overridden and vice versa. – ksuralta Mar 02 '14 at 14:01
1

Use a Set. From the JavaDoc:

A collection that contains no duplicate elements

If the order of the elements is important, then use a LinkedHashSet.

For proper working, Student must implement hashCode and equals methods or the single elements may not to be recognized as equal.

Peter Keller
  • 7,526
  • 2
  • 26
  • 29
0

There are several ways to do this one of which is to compare the objects being inserted by overriding the equals method in the Student class as follows:

public class Student {
    String name;
    public boolean equals(Object o) {
       Student s = (Student)o;
       return s.name.equals(this.name);
    }
}

and then you can check the object that you are inserting using the contains method like discussed in previous answer(s).

Thresh
  • 470
  • 6
  • 18
0

You can make use of HashMap to handle duplicate key names.

HashMap studentsMap = new HashMap( 10 );

if ( ! studentsMap.containsKey( "21" ) ) {
  studentsMap.put( "22", someStudent );
}

And if you really want to replace the duplicate, if exists or not one, then
you can directly put an object

  studentsMap.put( "22", someStudent );

If the map previously contained a mapping for the key, the old value is replaced.

Ravinder Reddy
  • 23,692
  • 6
  • 52
  • 82
0

Override the equals() and hashCode() appropriately and then utilise the contains() method as suggested my mbs.You can use the EqualsBuilder and HashCodeBuilder classes from Apache Commons Lang

Code:

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;

class Student {

    private int id;

    private String name;

    private int age;

    // CONSTRUCTORS

    public Student() {
        super();
    }

    public Student(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    // GETTERS AND SETTERS

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder(17, 37).append(id).append(name).append(age)
        .toHashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Student other = (Student) obj;

        return new EqualsBuilder().append(id, other.id)
        .append(name, other.name).append(age, other.age).isEquals();

    }

}

public class Main {

    public static void main(String[] args) {

        List<Student> students = new ArrayList<Student>();

        Student student1 = new Student(1, "Student Name 1", 18);

        Student student2 = new Student(2, "Student Name 2", 20);

        if (!students.contains(student1)) {

            students.add(student1);

            System.out.println("Student added");

        } else {

            System.out.println("DUPLICATE STUDENT");
        }

    }

}
Sandeep Chatterjee
  • 3,220
  • 9
  • 31
  • 47
0

Answer which is similar to the problem:

public class Main {
    
        public static void main(String[] args) {
    
            List<Student> students = new ArrayList<Student>();
    
            Student student1 = new Student(1, "Vikash", 18);
            Student student2 = new Student(2, "Akash", 20);
            Student student3 = new Student(3, "Arvik", 18);
            students.add(student1);
            students.add(student2);
            students.add(student3);
            
            //new students
            Student student5 = new Student(5, "Vikash", 20);

            boolean flag = false;

            for(Student s :students) {
                if(s.getName().equals(student5.getName())) {
                    s.setId(student5.getId());
                    flag = true;
                }
            }
            if(flag==false) {
                students.add(student5);
            }
    
            students.forEach(action-> System.out.println(action));
        }
    
    }
Vikash Kumar
  • 1,096
  • 11
  • 10