I’m wondering which of the following approaches I should use when finding an entry with an id from a collection?
Using a map
Map<String, MyObject> map = new HashMap<>();
public MyObject getById(String id) {
return map.get(id);
}
Using a list/set
List<MyObject> list = new ArrayList<>();
public MyObject getObjectById(String id) {
for (MyObject object : list) {
if (object.getId().equals(id)) {
return object;
}
}
return null;
}
Without having a specific use case, which would be recommended to use?
>Solution :
If you can use a HashMap, you absolutely should. Retrieving an item from a HashMap using its key takes a constant amount of time, but iterating through an array takes time proportional to the number of elements in the array. In more technical terms, the lookup using a HashMap is O(1), while the lookup using an ArrayList is O(n).
What that means is the code that uses a HashMap will always be fast, but the code that uses the ArrayList will slow down significantly as you add more elements to it.