Skip to content

Instantly share code, notes, and snippets.

@SungjinYoo
Last active November 13, 2018 12:08
Show Gist options
  • Save SungjinYoo/3a94b995bf5ea36a179b32ae65dbb52e to your computer and use it in GitHub Desktop.
Save SungjinYoo/3a94b995bf5ea36a179b32ae65dbb52e to your computer and use it in GitHub Desktop.
interface Consumer<T> {
void accept(T value);
}
// create Consumer by defining a class explicitly
class HelloWorldPrinter implements Consumer<String> {
public void accept(String name) {
System.out.println("Hello World! " + name);
}
}
HelloWorldPrinter printer1 = new HelloWorldPrinter();
printer1.accept("SJ"); // prints out "Hello World! SJ"
// method reference from existing ones
Consumer<String> reference = printer1::accept;
reference.accept("SJ"); // also prints out "Hello World! SJ"
// create Consumer with anonymous class
Consumer<String> printer2 = new Consumer<>() {
@Override
public void accept(String name) {
System.out.println("Hello World! " + name);
}
};
printer2.accept("SJ"); // also prints out "Hello World! SJ"
// create Consumer with lambda expression
Consumer<String> printer3 = (name) -> {
System.out.println("Hello World! " + name);
};
printer3.accept("SJ"); // also prints out "Hello World! SJ"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment