Skip to content

Instantly share code, notes, and snippets.

@cheinema
Created November 19, 2011 09:53
Show Gist options
  • Save cheinema/1378668 to your computer and use it in GitHub Desktop.
Save cheinema/1378668 to your computer and use it in GitHub Desktop.
Demo of Lambda Expressions
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