0

I have an ArrayList of objects where each object contains a string 'word' and a date. I need to check to see if the date has passed for a list of 500 words. The ArrayList could contain up to a million words and dates. The dates I store as integers, so the problem I have is attempting to find the word I am looking for in the ArrayList.

Is there a way to make this faster? In python I have a dict and mWords['foo'] is a simple lookup without looping through the whole 1 million items in the mWords array. Is there something like this in java?

    for (int i = 0;  i < mWords.size();  i++) {
        if ( word == mWords.get(i).word ) {
           return mWords.get(i);
        }
    }  

4 Answers 4

2

If the words are unique then use HashMap. I mean, {"a", 1}, {"b", 2}

Map<String, Integer> wordsAndDates = new HashMap<String, Integer>();
wordsAndDates.put("a", 1);
wordsAndDates.put("b", 2);

and wordsAndDates.get("a") return 1

If not you shouldn't use HashMap because it overrides previous value. I mean

wordsAndDates.put("a", 1);
wordsAndDates.put("b", 2);
wordsAndDates.put("a", 3);

and wordsAndDates.get("a") return 3

In such case you can use ArrayList and search in it

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

2 Comments

Thanks guys! And thanks for the warning as it explains to me how the HashMap works.
you are welcome. it rejoices me that you learn something new today
1

If you're not stuck with an ArrayList you should use some kind of hash based data structure. In this case it seems like a HashMap should fit nicely (it's pretty close to python's dict). This will give you an O(1) lookup time (compared to your current method of linear search).

Comments

1

You want to use a Map in Java

Map<String,Integer> mWords = new HashMap<String, Integer>();
mWords.put ("foo", 112345);

Comments

0

What about Collections.binarySearch() (NB: the list must be sorted) if ou are stuck with the ArrayList

Comments

Your Answer

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