“Get” a Collection Element By Index Without Creating a New List or Array
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.