Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Should I use a Map storing the id, or iterate over entries to find an object?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading