Created
June 25, 2020 07:44
-
-
Save zalito12/0e84ace20c2e5ad61eecd28754fde88b to your computer and use it in GitHub Desktop.
Java wrapper class to write functional code
This file contains 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 static java.util.Objects.isNull; | |
import static java.util.Objects.nonNull; | |
import java.util.function.Consumer; | |
import java.util.function.Function; | |
import java.util.function.Supplier; | |
import javax.annotation.Nullable; | |
public class Pipe<E> { | |
private E entity; | |
private Pipe() { | |
} | |
private Pipe(E entity) { | |
this.entity = entity; | |
} | |
public static <T> Pipe<T> of(T entity) { | |
return new Pipe<>(entity); | |
} | |
public <E2> Pipe<E2> map(Function<E, E2> transformer) { | |
Pipe<E2> pipe = new Pipe<>(null); | |
if (nonNull(entity)) { | |
pipe.entity = transformer.apply(entity); | |
} | |
return pipe; | |
} | |
public <E2> Pipe<E2> flatMap(Function<E, Pipe<E2>> transformer) { | |
Pipe<E2> pipe = new Pipe<>(null); | |
if (nonNull(entity)) { | |
pipe.entity = transformer.apply(entity).entity; | |
} | |
return pipe; | |
} | |
public Pipe<E> tap(Consumer<E> transformer) { | |
if (nonNull(entity)) { | |
transformer.accept(entity); | |
} | |
return this; | |
} | |
@Nullable | |
public E get() { | |
if (nonNull(entity)) { | |
return entity; | |
} else { | |
throw new RuntimeException(); | |
} | |
} | |
public E orGet(E fallbackEntity) { | |
if (isNull(entity)) { | |
return fallbackEntity; | |
} | |
return entity; | |
} | |
public E orElseGet(Supplier<E> fallback) { | |
if (isNull(entity)) { | |
return fallback.get(); | |
} | |
return entity; | |
} | |
public static void main(String[] args) { | |
String copperPipe = Pipe.of("This") | |
.map((pipe) -> new StringBuilder(pipe).append(" is")) | |
.map((pipe) -> pipe.append(" a")) | |
.map((pipe) -> pipe.append(" copper")) | |
.tap(System.out::println) | |
.flatMap((pipe) -> Pipe.of(new StringBuilder(pipe).append(" pipe"))) | |
.map(StringBuilder::toString) | |
.get(); | |
System.out.println(copperPipe); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment