Tushar Banne
Tushar Banne

Reputation: 1725

Is it a good option to use contains() method of ArrayList in nested for loops w.r.t performance?

List<Employee> empsFromDB = repo.findAll(); //size m

List<Long> empIdsFromReq = req.getEmployeeIds();// size n

for(Employee emp: empsFromDB){
   empIdsFromReq.contains(emp.getEmployeeId());
}

Is the above code optimum w.r.t performance?

My approach has been to create a map of employee Ids as key and Employee as value and then retrieve the employees from map using the list of Ids.

My understanding is by using the second approach worst case is m+n operations whereas in the first approach its m x n, which I feel is not optimum.

Please advice.

Upvotes: 1

Views: 93

Answers (1)

Sandeepa
Sandeepa

Reputation: 3755

If you can use a HashSet instead of a List you can improve performance.

contains() for a HashSet is O(1) compared to O(n) for a List, therefore you should never use a List if you can do it with a HashSet.

Upvotes: 2

Related Questions