Last active
December 15, 2015 11:59
-
-
Save qnoid/5256788 to your computer and use it in GitHub Desktop.
An example showing the new syntactic sugar for constructor reference and lambda expressions introduced in Java 8. Inspired by http://www.techempower.com/blog/2013/03/26/everything-about-java-8/
This file contains hidden or 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.List; | |
import java.util.ArrayList; | |
import java.util.Arrays; | |
import java.util.function.Supplier; | |
import java.util.function.UnaryOperator; | |
class Person | |
{ | |
String name; | |
int age; | |
public String toString(){ | |
return String.format("%s, %d", this.name, this.age); | |
} | |
} | |
class Developer extends Person | |
{ | |
String language; | |
public String toString(){ | |
return String.format("%s, %s", super.toString(), this.language); | |
} | |
} | |
public class Builder<T> | |
{ | |
@FunctionalInterface | |
public interface Lambda<T> | |
{ | |
public T build(T t); | |
} | |
private final Supplier<T> supplier; | |
private Lambda<T> lambda; | |
public Builder(Supplier<T> supplier) | |
{ | |
this.supplier = supplier; | |
} | |
public Builder<T> lambda(Lambda<T> lambda){ | |
this.lambda = lambda; | |
return this; | |
} | |
public T build(){ | |
return this.lambda.build(this.supplier.get()); | |
} | |
public T build(UnaryOperator<T> unary){ | |
return unary.apply(this.supplier.get()); | |
} | |
public static void main(String... args) | |
{ | |
Builder<Person> personBuilder = new Builder<Person>(Person::new); | |
Person person = personBuilder.lambda( p -> { p.name = "Markos"; p.age = 33; return p; } ).build(); | |
System.out.println(person); | |
Builder<Developer> developerBuilder = new Builder<Developer>(Developer::new); | |
Developer developer = developerBuilder.lambda( d -> { d.name = "Markos"; d.age = 33; d.language = "Java"; return d; } ).build(); | |
System.out.println(developer); | |
Builder<List<String>> listBuilder = new Builder<List<String>>(ArrayList::new); | |
List<String> strings = listBuilder.build( l -> { l.add("foo"); l.add("bar"); return l; } ); | |
//strings.forEach( System.out::println ); | |
for(String s : strings){ | |
System.out.println(s); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for the heads up @michaelhixson.
Didn't know about that :)
Have now updated the post to show that as well.
For some reason the forEach get a symbol not found in Java b82.
Is it not implemented yet?