0

Recently I had a technical discussion in one interview process. He asked me below scenario,

Class Employee
{
   int empId;
   String empName;
   String salary;
}

Now I'm storing 1000 (This could go high) employee object in an Arraylist. What is the best way in terms of time complexity, wherein I could search by empName from this list.

Can anyone please suggest the best possible way for this...?

2 Answers 2

1

You could store the elements in a HashMap<String, Employee>, which is indexed by the employee name, and the value contains the Employee object.

This gives you O(1) (average case) lookup for ID lookup.

Another option, if you wish to keep using your ArrayList to store the objects, is to have it sorted (using a custom Comparator) by the empName, and then find the relevant item in O(logn) using Collections.binarySearch()

Sign up to request clarification or add additional context in comments.

2 Comments

I suggested this answer, but then he changed the question by saying now I want to search by empId, would you create new map implementation for it..? And after that I suggested if that is the case we'll sort it out and then we'll loop it in and search to avoid any further records to traverse... But then he said okay leave it lets move ahead...
If you want to start looking for all, or many, of the fields in your object, you are looking for some kind of SQL like DS, Read more about Relational databases
1
employees.stream().filter(e -> "name".equals(e.getEmpName())).collect(Collectors.toList());

using stream api and filter java 8

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.