Created
August 1, 2012 10:32
-
-
Save jthoenes/3225689 to your computer and use it in GitHub Desktop.
Testing the Lambda Water
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is by far the most concise and clear example I've seen for Java 8 Lambdas. Kudos.