I have an ArrayList of items, itemList. Item has a property author. I need a
list of items where the author is a specific author. The following code
works, but is there a better way to do this?
ArrayList<Item> itemList1 = new ArrayList<Item>();
for( Item item: itemList)
{
if( author.equals( item.author() ))
{
itemList1.add( item );
}
}
return itemList1;
Arne Vajhøj - 20 Feb 2007 01:44 GMT
> I have an ArrayList of items, itemList. Item has a property author. I need a
> list of items where the author is a specific author. The following code
[quoted text clipped - 9 lines]
> }
> return itemList1;
Use a HashMap either instead or as supplement to the ArrayList.
Arne
Mark Rafn - 20 Feb 2007 18:47 GMT
>I have an ArrayList of items, itemList. Item has a property author. I need a
>list of items where the author is a specific author. The following code
>works, but is there a better way to do this?
>ArrayList<Item> itemList1 = new ArrayList<Item>();
> for( Item item: itemList)
[quoted text clipped - 5 lines]
> }
>return itemList1;
That's about all you can do if you don't want to write some code to make it
faster. You could, instead of using ArrayList<Item>, define a class ItemList,
which has a list of items, but also a hash of author to list of items, and any
other cached sublists you want.
--
Mark Rafn dagon@dagon.net <http://www.dagon.net/>
Daniel Pitts - 20 Feb 2007 19:17 GMT
On Feb 19, 5:49 pm, "Ook" <Ook Don't send me any freakin' spam at
zootal dot com delete the Don't send me any freakin' spam> wrote:
> I have an ArrayList of items, itemList. Item has a property author. I need a
> list of items where the author is a specific author. The following code
[quoted text clipped - 9 lines]
> }
> return itemList1;
That is one way to do it unless you build an index before hand:
/* Initialize in the constructor.
Probably to a HashMap, depending on your Author class. */
private final Map<Author, Collection<Item>> itemsByAuthor;
public void buildAuthorIndex(Collection<Item> items) {
for (Item item: items) {
Collection<Item> forAuthor = itemsByAuthor.get(item.author());
if (forAuthor == null) {
forAuthor = new ArrayList<Item>();
itemsByAuthor.put(item.author(), forAuthor);
}
forAuthor.add(item);
}
}
public Collection<Item> getItemsForAuthor(Author author) {
Collection<Item> items = itemsByAuthor.get(author);
if (itemsByAuthor == null) {
return java.util.Collections.emptyList();
/* You might also consider returning a new ArrayList instead.
*/
}
return items;
}
As you can see, this approach is a little bit more verbose, and
requires more memory. It also assumes that once you've built your
Item list, you aren't updating it (although, this can be easily
accounted for).
Use this approach only when: You find that your application is too
slow, and a profiler points to your existing approach as being the
culprit.
Remember this basic tenet of Software Engineering: Make it work
right, then make it work fast-enough.