Re: for :each style question
On 30/11/11 23:32, Roedy Green wrote:
In a for:each loop, sometimes you want to treat the first and or last
element specially. [...]
What do you consider the best style to deal with this?
If I needed it a lot...
import java.util.Arrays;
import java.util.List;
public class FirstLastLoop {
interface FirstLastBlock<T> {
void invoke(T t, boolean isFirst, boolean isLast);
}
static<T> void forEach(Iterable<? extends T> coll,
FirstLastBlock<? super T> block) {
boolean isFirst = true;
boolean lastHeld = false;
T last = null;
for (T t : coll) {
if (lastHeld) {
block.invoke(last, isFirst, false);
isFirst = false;
}
last = t;
lastHeld = true;
}
if (lastHeld)
block.invoke(last, isFirst, true);
}
public static void main(String[] args) throws Exception {
List<String> list = Arrays.asList(args);
FirstLastBlock<String> block = new FirstLastBlock<String>() {
public void invoke(String t, boolean isFirst, boolean isLast) {
if (isFirst)
System.out.print("The list: ");
else if (isLast)
System.out.print(" and ");
else
System.out.print(", ");
System.out.print(t);
if (isLast)
System.out.println('.');
}
};
forEach(list, block);
// Lambda version
forEach(list, (t, isFirst, isLast) -> {
if (isFirst)
System.out.print("The list: ");
else if (isLast)
System.out.print(" and ");
else
System.out.print(", ");
System.out.print(t);
if (isLast)
System.out.println('.');
});
}
}
--
ss at comp dot lancs dot ac dot uk