Skip to content

Instantly share code, notes, and snippets.

@rokon12
Created August 13, 2020 15:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rokon12/a8ddb39b7690b60e05466a511a1ff944 to your computer and use it in GitHub Desktop.
Save rokon12/a8ddb39b7690b60e05466a511a1ff944 to your computer and use it in GitHub Desktop.
package org.jugbd.quiz;
import java.util.function.Function;
import java.util.stream.Stream;
import static org.jugbd.quiz.Coffee.CoffeeDecoratorUsingLambda.getCoffeeWithExtras;
@FunctionalInterface
public interface Coffee {
String getIngredient();
static Coffee withSaltedCaramelFudge(Coffee coffee) {
return () -> coffee.getIngredient() + " +Salted caramel fudge";
}
static Coffee withSweetenedMilk(Coffee coffee) {
return () -> coffee.getIngredient() + " + Sweetened Milk";
}
static Coffee withDarkCookieCrumb(Coffee coffee) {
return () -> coffee.getIngredient() + " + Dark Cookie Crumb";
}
static Coffee withVanillAlmondExract(Coffee coffee) {
return () -> coffee.getIngredient() + " + Vanilla/almond extract";
}
class CoffeeDecoratorUsingLambda {
public static Coffee getCoffeeWithExtras(Coffee coffee, Function<Coffee, Coffee>... ingradiants) {
Function<Coffee, Coffee> reduced = Stream.of(ingradiants).reduce(Function.identity(), Function::andThen);
return reduced.apply(coffee);
}
}
class CoffeeApp {
public static void main(String[] args) {
var coffee = getCoffeeWithExtras(() -> "Main Ingredient",
Coffee::withDarkCookieCrumb,
Coffee::withSweetenedMilk,
Coffee::withVanillAlmondExract);
System.out.println(coffee.getIngredient());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment