Raghavendra Raghavendra - 5 months ago 7
Java Question

Condition to check if a value exists in list containing objects,

I am trying to write an if condition to check a value exists in a list containing many objects,
Here is my code:

List<TeacherInfo> teacherInfo=ServiceManager.getHelperService(TeacherManagementHelper.class, request, response).getTeacherInfoId();
if(teacherInfo.contains(inputParam))
{
out2.println("<font color=red>");
out2.println("Id Not Available");
out2.println("</font>");
}
else
{
out2.println("<font color=green>");
out2.println("Id Available");
out2.println("</font>");
}


after executing 1st sentence
getTeacherInfoId()
method successfully returns a list of objects, in those objects I want to check any object has a value same as
inputParam
. Is my above code right ? if wrong please help me .

Answer

contains(Object o) is internally based on equals between objects of your list and your input, as stated by the doc.

Since you said that inputParam is an integer, then the current state of your code is wrong because you compare an integer to TeacherInfo objects, so they won't ever be equal. I believe you want to compare inputParam to one particular field of TeacherInfo objects.

If you're using Java 8, you can use the stream API instead of contains():

if (teacherInfos.stream().anyMatch(ti -> ti.getId() == inputParam)) {
    // contains the id
} else {
    // does not contain the id
}

For previous java versions, an alternative to contains() would be to iterate over your list and compare manually your integer to the TeacherInfo's field:

boolean contains = false;
for (TeacherInfo ti : teacherInfos) {
    if (ti.getId() == inputParam) { // I used getId(), replace that by the accessor you actually need
        contains = true;
        break;
    }
}
if (contains) {
    // contains the id
} else {
    // does not contain the id
}

Note: If you don't need other information than the ID itself, I'd rather suggest to return the list of IDs from a method called getTeacherIds(), especially if this information comes from a DB.

Comments