Faisal Khan
Faisal Khan

Reputation: 2614

How to remove duplicate objects in a List<MyObject> without using any collection and loop

Is there any way to remove duplicate element from arraylist without using any collections and loop.

Below is my program and rollNumber is unique for every student.

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

public class TestJava {

    private List<Student> dataList;

    public static void main (String[] args){
        TestJava testJava=new TestJava();
        testJava.insertRecord();
        testJava.showRecords();

    }

    private void showRecords(){

        for (Student student:dataList){
            System.out.println("====================================");
            System.out.println("RollNumber : "+student.rollNumber);
            System.out.println("Name : "+student.name);
            System.out.println("Age : "+student.age);
            System.out.println("");

        }

    }

    private void insertRecord(){
        dataList=new ArrayList<>();
        dataList.add(new Student(1,"Prateek",29));
        dataList.add(new Student(2,"Faisal",27));
        dataList.add(new Student(3,"Ram",24));
        dataList.add(new Student(4,"Shashank",25));

        dataList.add(new Student(1,"Prateek",29));
        dataList.add(new Student(2,"Faisal",27));
        dataList.add(new Student(3,"Ram",24));
        dataList.add(new Student(4,"Shashank",25));

    }
}

class Student{

    public int rollNumber;
    public String name;
    public int age;

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

Upvotes: 0

Views: 96

Answers (1)

xingbin
xingbin

Reputation: 28279

You need define equals and hashCode in Student class first.

In Java8, you can do it by

list = list.stream()
        .distinct()
        .collect(Collectors.toList());

Upvotes: 4

Related Questions