Detecting the first iteration through a for-each loop in Java

One simpler way for this situation is to note that you can always append an empty string: // For the first iteration, use a no-op separator String currentSeparator = “”; for (String s : list) { builder.append(currentSeparator); builder.append(s); // From the second iteration onwards, use this currentSeparator = separator; } Alternatively (and preferrably) use Guava’s … Read more

Enhanced for loop compiling fine for JDK 8 but not 7

This should actually compile fine for JDK 7 and 8. Quoting JLS section 14.14.2 (which is the same for the Java 7 specification): The enhanced for statement is equivalent to a basic for statement of the form: for (I #i = Expression.iterator(); #i.hasNext(); ) { {VariableModifier} TargetType Identifier = (TargetType) #i.next(); Statement } Rewriting the … Read more

How to iterate with foreach loop over java 8 stream

By definition foreach loop requires an Iterable to be passed in. It can be achieved with anonymous class: for (String s : new Iterable<String>() { @Override public Iterator<String> iterator() { return stream.iterator(); } }) { writer.append(s); } This can be simplified with lambda because Iterable is a functional interface: for (String s : (Iterable<String>) () … Read more

tech