2

I have an ArrayList of custom objects I called Questions. These Questions contain the question, a unique ID, and an ArrayList of Answers. Now I'm trying to search for the question with a specific unique ID. This is what I'm currently doing but I'm worried this might take too long for a big list, so I was wondering if there was a faster way to do this.

public Question getQuestion(String idLookingFor) {
    for (Question question : questions) {
        if (question.getId().equals(idLookingFor))
            return question;
    }
    return null;
}

1 Answer 1

5

You can use HashMap for storing the information about ID as key and Question as value. I am assuming, ID is stored as Interger.

Map<Integer, Question> map = new HashMap<>();

The Map will provide you O(1) time complexity for searching the question.

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

2 Comments

Thanks! I can't believe I forgot about Map!
Yes, storing in both containers, surprising (List and Map) at first look, but give fast information: order what item was added (list) and fast search by key via Map. Use such pattern once in a month, id works goog.

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.