Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looking for value in List

I have List declared as

        private List<Employees> employees;

and in I am getting values from database using DAO as

        employees= new ArrayList<Employees>();
        employees.addAll(myDAO.getEmployees());

I would like to search for a value in employees List, what is the best approach for looking for a value in employees List?

I have tried

    Collections.sort(employees);
    int index = Collections.binarySearch(employees, "abc");

However I am getting cast Exception

Any help is highly appreciated.

Thanks

like image 530
Jacob Avatar asked Jun 09 '26 16:06

Jacob


2 Answers

Collections.sort(employees); // BigO - nlog(n)
int index = Collections.binarySearch(employees, new Employee("abc",...)); // BigO - log(n)

if you sort every time your list and search it, Code complexity would be nlog(n) + log(n) where nlog(n) for sorting list and log(n) for binary search.

It is better if you search your list linearly. liner search would take BigO - n which perform better than previous approach.


You are getting cast Exception in Collections#sort method because of your list contain null value which unable to cast Employee and raise ClassCastException

like image 171
Subhrajyoti Majumder Avatar answered Jun 11 '26 12:06

Subhrajyoti Majumder


Employees lookingForValue(String value, List<Employees> employees)
{
    for (Employees employee : employees)
    {
       if (value.equals(employee.getFieldValue()))
       {
          return employee;
       }
    }
    return null;
}  

usage

lookingForValue("abc", employees);
like image 39
Ilya Avatar answered Jun 11 '26 11:06

Ilya