Atom Feed SITE FEED   ADD TO GOOGLE READER

Coding in the small with Google Collections: Iterables.concat()

Part 7 in a Series.

Iterables.concat() combines multiple iterables (such as ArrayList and HashSet) so you can go through multiple collections' elements in a single pass:

Before:

  public boolean orderContains(Product product) {
List<LineItem> allLineItems = new ArrayList<LineItem>();
allLineItems.addAll(getPurchasedItems());
allLineItems.addAll(getFreeItems());

for (LineItem lineItem : allLineItems) {
if (lineItem.getProduct() == product) {
return true;
}
}

return false;
}


After:

  public boolean orderContains(Product product) {
for (LineItem lineItem : Iterables.concat(getPurchasedItems(), getFreeItems())) {
if (lineItem.getProduct() == product) {
return true;
}
}

return false;
}


If ever you only have the Iterator and not the Iterable, the equivalent method is Iterators.concat. As a special treat, both concat methods are optimized so that they don't need a private collection.

Part 8