I made this Student ArrayList that have name, age and number variable. I manually input 3 student. I want to check if a name already exist in my list. I tried to use list.contains but it seems not working. Are there certain way to do for this kind of ArrayList?
public class CompareToeX {
public static void main(String[] args) {
ArrayList<Student> obj=new ArrayList<Student>();
obj.add(new Student("Peter", 27,1));
obj.add(new Student("John",26,7));
obj.add(new Student("Jack",21,5));
if(obj.contains("Peter")){
System.out.println("Peter on is on the list!");
} else {
System.out.println("Peter is not on the list!");
}
}
}
This is the Student class
public class Student{
private String studentName;
private int age;
private int rollno;
public Student(String studentName, int age, int rollno){
this.studentName=studentName;
this.age=age;
this.rollno=rollno;
}
public String getStudent(){
return studentName;
}
public int getAge(){
return age;
}
public int getRollno(){
return rollno;
}
public void setStudent(String Student){
studentName=Student;
}
public void setAge(int age){
this.age=age;
}
public void setRollno(int rollno){
this.rollno=rollno;
}
}
After i run, the result should show that peter is on the list right. But it goes the other way around. It seems that the contains method is not working.
CodePudding user response:
A student isn't a name.
.contains()
will fail here because the string "Peter"
is not in the list. It obviously isn't; how could it be? This list only contains Student objects, not Strings, after all.
You'll have to write a for loop, or use streams.
boolean peterIsInTheList = false;
for (var s : students) {
if (s.getName().equals("peter")) peterIsInTheList = true;
}
or
boolean peterIsInTheList = students.stream()
.anyMatch(s -> s.getName().equals("peter"));
Alternatively you could use the idea of a map; change your data structure. Instead of using a list, have a map that maps first names onto student objects:
Map<String, Student> students = new HashMap<>();
students.put("peter", new Student(....));
if (students.containsKey("peter")) {
// peter is in the list
}
CodePudding user response:
You are checking if the String
Peter
is in the list, or the list only contains Student
object. So you can only check if Student
is contained inside the list (be sure to implement the right equals
/hashcode
method if you wish to use .contains
).
This will do
obj.stream()
.filter(student -> student.getStudent().contains("Peter"))
.findFirst()
.ifPresentOrElse(student -> System.out.println("Peter on is on the list!"), () -> System.out.println("Peter is not on the list!"));
CodePudding user response:
Being not a default data type, I think you need to override some functions of ArrayList first, like the .compare() one.
It was answered here too Java: to use contains in a ArrayList full of custom object should I override equals or implement Comparable/Comparator?