Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!aioe.org!.POSTED!not-for-mail From: Steven Simpson Newsgroups: comp.lang.java.programmer Subject: Re: for :each style question Date: Sun, 04 Dec 2011 19:43:18 +0000 Organization: Aioe.org NNTP Server Lines: 72 Message-ID: References: <30fdd7tlkkejm29ufduhc9nnfk7uu3c6h0@4ax.com> NNTP-Posting-Host: 3JnaVNumoybW/sOwRjlcjw.user.speranza.aioe.org Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit X-Complaints-To: abuse@aioe.org User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:8.0) Gecko/20111124 Thunderbird/8.0 X-Notice: Filtered by postfilter v. 0.8.2 Xref: x330-a1.tempe.blueboxinc.net comp.lang.java.programmer:10492 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 { void invoke(T t, boolean isFirst, boolean isLast); } static void forEach(Iterable coll, FirstLastBlock 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 list = Arrays.asList(args); FirstLastBlock block = new FirstLastBlock() { 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