I have a List for example
{ "in" , "out", "rec", "auth" }
... but the content of the list is not predictable.
When iterating the list list how can we know we have reached last element? I want to apply different logic for the last element.
I have a List for example
{ "in" , "out", "rec", "auth" }
... but the content of the list is not predictable.
When iterating the list list how can we know we have reached last element? I want to apply different logic for the last element.
Example : List list = new ArrayList be the list, you need not traverse to get the last( element, you can get it by list.get(list.size()-1) and perform the logic you wanted.
The "classic" way to iterate through a Java List
is to use List.iterator()
to obtain an Iterator
, then use the Iterator
's methods to step through the list values.
This works with anything that implements Iterable
, not just Lists.
// assuming myList implements Iterable<Type>
Iterator<Type> iterator = myList.iterator();
while(iterator.hasNext()) {
doSomethingWith(iterator.next())
}
Since JDK 1.5, there has been a shortcut in the language to achieve the same thing:
// assuming myList implements Iterable<Type>
for(Type item : myList) {
doSomethingWith(item);
}
However, while convenient in many situations, this syntax doesn't give you full access to all the information Iterator
has.
If you want to treat the last element of the list specially, one method might be:
Iterator<Type> iterator = myList.iterator();
while(iterator.hasNext()) {
Type item = iterator.next();
if(iterator.hasNext() {
doSomethingWith(item);
} else {
// last item
doSomethingElseWith(item);
}
}
Your specific situation - creating a comma-separated string representation of the list, without a trailing comma:
Iterator<String> iterator = myList.iterator();
StringBuilder buffer = new StringBuilder();
while(iterator.hasNext()) {
buf.append(iterator.next());
if(iterator.hasNext() {
buf.append(",")
}
}
All this assumes that there's a reason you want to avoid using list.size().
You should consider using LinkedList
instad of ArrayList. It has getLast()
method.