Getting an instance of class X from ArrayList of class X out of position

If I have ArrayList

in Java 6 program:

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

Where a Keyword

has int keywordNo

, String text

, int frequency

and a few other fields.

How do I get an item from ArrayList

if I know keywordText

but not the item's position or field value keywordNo

?

I know that I could use a loop and just read the ArrayList

comparison Strings

until I find the item, but is there any better alternative?

+3


source to share


1 answer


You will need to iterate over each item in the list using a loop. For each iteration, you will need to get the current element and check its value.

For faster access, you should use Map<String, Keyword>

where String is the Text keyword.

You can place your keywords on the 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 specific keyword, you can make a call like this:

Keyword result = keywordsMap.get("somekeyword");

      

+2


source







All Articles