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
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
Employees lookingForValue(String value, List<Employees> employees)
{
for (Employees employee : employees)
{
if (value.equals(employee.getFieldValue()))
{
return employee;
}
}
return null;
}
usage
lookingForValue("abc", employees);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With