Skip to content

Instantly share code, notes, and snippets.

@jthoenes
Created August 1, 2012 10:32
Show Gist options
  • Save jthoenes/3225689 to your computer and use it in GitHub Desktop.
Save jthoenes/3225689 to your computer and use it in GitHub Desktop.
Testing the Lambda Water
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);
}
}
@chamakits
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment