3

If I have an ArrayList in a Java 6 program as follows:

ArrayList<Keyword> = new ArrayList<Keyword>();

Where a Keyword has an int keywordNo, String text, int frequency and a few other fields.

How can I retrieve an element from the ArrayList if I know the keywordText but not the position of the element or the value of field keywordNo?

I know that I could use a loop and simply read through the ArrayList comparing Strings until I find the element but is there any better alternative?

4
  • Would it be possible to have more than one Keyword object matching a given keywordText? Commented Apr 30, 2015 at 22:46
  • No, they should be unique. Commented Apr 30, 2015 at 22:49
  • The List interface has an indexOf() method which returns the index of a given input Object, but it uses the equals() method which might not work for your case if the other fields in a Keyword be unknown. Commented Apr 30, 2015 at 22:56
  • I would rather avoid writing my own dedicated equals method for the class in question. Commented Apr 30, 2015 at 22:58

1 Answer 1

2

You would have to iterate over every element in the list with a loop. For each iteration you will need to get the current element and check its value.

For faster access you should use a Map<String, Keyword> where the String is the keywordText.

You can put your keywords in a Map like this:

Map<String, Keyword> keywordsMap = new HashMap<String, Keyword>();
for (Keyword k : keywordList) {
    keywordsMap.put(k.text, k);
}

Then if you want to access a particular Keyword you can make a call like this:

Keyword result = keywordsMap.get("somekeyword");
Sign up to request clarification or add additional context in comments.

3 Comments

And q.v. this SO post which also came to the same conclusion.
Yes, this is just what I think I will have to do.
And have a break statement in the loop as well.

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.