Thursday, July 23, 2009

Iterating Collections in Java

There are a number of ways to iterate over Collections. The old and tedious method is to use iterators and a for loop or while hasNext(). In recent years you can instead use an EntrySet.

Here's a pretty good sampling of the methods available:

http://hanuska.blogspot.com/2006/08/improved-map-iteration_13.html

And my own iteration over a set:

// assumes Map<String, String> stuffAttributes exists in scope
Set<Stuff> attributes = new HashSet<Stuff>();
Boolean success = true;

for (Map.Entry<String, String> prmEntry : stuffAttributes.entrySet()) {
StuffAttribute attribute = new UserNotificationsAttribute();
attribute.setAttributeKey(prmEntry.getKey());
attribute.setAttributeValue(prmEntry.getValue());
if (!attributes.add(attribute)) {
success = false;
}
}
un.setStuffAttributeSet(attributes);

No comments:

Labels

Blog Archive

Contributors