Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

list

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 .

like image 549
Raghavendra Avatar asked Apr 28 '14 08:04

Raghavendra


1 Answers

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 can't work 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():

List<TeacherInfo> teacherInfo=ServiceManager.getHelperService(TeacherManagementHelper.class, request, response).getTeacherInfoId();
if (teacherInfo.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:

private static boolean containsTeacherId(List<TeacherInfo> teacherInfos, int id) {
    for (TeacherInfo ti : teacherInfos) {
        if (ti.getId() == inputParam) { // I used getId(), replace that by the accessor you actually need
            return true;
        }
    }
    return false;
}

Then:

List<TeacherInfo> teacherInfo=ServiceManager.getHelperService(TeacherManagementHelper.class, request, response).getTeacherInfoId();
if (containsTeacherId(teacherInfo, inputParam)) {
    // 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.

like image 183
Joffrey Avatar answered Sep 21 '22 13:09

Joffrey