public
Last active

Testing the Lambda Water

  • Download Gist
LambdaIntro.java
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
package net.jthoenes.blog.spike.lambda;
 
import java.util.Arrays;
import java.util.List;
 
public class LambdaIntro {
 
 
public static interface ItemWithIndexVisitor<E> {
public void visit(E item, int index);
}
 
public static <E> void eachWithIndex(List<E> list, ItemWithIndexVisitor<E> visitor) {
for (int i = 0; i < list.size(); i++) {
visitor.visit(list.get(i), i);
}
}
 
 
public static void main(String[] args) {
List<String> list = Arrays.asList("A", "B", "C");
eachWithIndex(list,
(value, index) -> {
String output = String.format("%d -> %s", index, value);
System.out.println(output);
}
);
 
eachWithIndex(list, LambdaIntro::printItem);
}
 
public static <E> void printItem(E value, int index) {
String output = String.format("%d -> %s", index, value);
System.out.println(output);
}
 
 
}

This is by far the most concise and clear example I've seen for Java 8 Lambdas. Kudos.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.