如何在不使用任何收集和循环的情况下删除List <myobject>中的重复对象

时间:2018-07-08 11:32:34

标签: java arraylist collections

有什么方法可以在不使用任何集合和循环的情况下从arraylist中删除重复的元素。

下面是我的程序,rollNumber对于每个学生都是唯一的。

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;
    }
}

1 个答案:

答案 0 :(得分:4)

您首先需要在equals类中定义hashCodeStudent

在Java8中,您可以通过

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