“Get” a Collection Element By Index Without Creating a New List or Array

Posted on September 25, 2006. Filed under: java |

More than a few times I’ve found myself needing the first element of a collection, and that collection wasn’t a List, with its nice get function. So I’ve ended up writing collection.iterator().next(), which just feels wrong. I’m not iterating.

Common Collections has a nice tool for this need: CollectionUtils.get(…). It can take a Map, List, Array, Set, Iterator, or Enumeration, and return the element at an index you specify. For example:


Set songs = new HashSet();
songs.add("Frankenstein");
songs.add("Just Got Paid");
System.out.println(songs.iterator().next());
System.out.println(CollectionUtils.get(songs, 0));

Mind you still have to check bounds.

Make a Comment

Make a Comment: ( None so far )

blockquote and a tags work here.

  • Category Cloud

  • Twitter

  • Del.icio.us Links

Liked it here?
Why not try sites on the blogroll...