Created
November 19, 2011 09:53
-
-
Save cheinema/1378668 to your computer and use it in GitHub Desktop.
Demo of Lambda Expressions
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
import java.util.HashMap; | |
import java.util.Map; | |
public class Lambda { | |
enum Attribute { NAME, AGE }; | |
interface ToString<T> { String toString(T object); }; | |
public static void main(final String[] args) throws Exception { | |
final Map<Attribute, ToString<Person>> mapping = new HashMap<>(); | |
// Here are the Lambda Expressions | |
mapping.put(Attribute.NAME, Person#getName); | |
mapping.put(Attribute.AGE, (p) -> Integer.toString(p.getAge())); | |
final Person person = new Person("Scott", 29); | |
System.out.printf("%s is %s.\n", | |
mapping.get(Attribute.NAME).toString(person), | |
mapping.get(Attribute.AGE).toString(person)); | |
} | |
} | |
class Person { | |
private final String name; | |
private final int age; | |
public Person(final String name, final int age) { | |
this.name = name; | |
this.age = age; | |
} | |
public String getName() { return name; } | |
public int getAge() { return age; } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment