Skip to content

Instantly share code, notes, and snippets.

@qnoid
Last active December 15, 2015 11:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save qnoid/5256788 to your computer and use it in GitHub Desktop.
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/
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);
}
}
}
@michaelhixson
Copy link

I realize you're just experimenting, and making your own functional interface is a part of that, but I can't help pointing out that you could use the built-in java.util.function.UnaryOperator interface instead of your Lambda interface. They're the same.

@qnoid
Copy link
Author

qnoid commented Mar 27, 2013

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment