Skip to content

Instantly share code, notes, and snippets.

@rbe
Last active January 2, 2023 18:39
Show Gist options
  • Save rbe/c9922b09fdc46712002c to your computer and use it in GitHub Desktop.
Save rbe/c9922b09fdc46712002c to your computer and use it in GitHub Desktop.
Java 8 Lambdas
import java.util.Arrays;
import java.util.Comparator;
import java.util.function.Consumer;
import java.util.function.Supplier;
public class Main {
private static void sort(String[] strings, Comparator comp) {
Arrays.sort(strings, comp);
}
@FunctionalInterface
interface Action {
void perform();
}
static class Action2<T> implements Consumer<T> {
@Override
public void accept(T t) {
System.out.println(this + ".accept: " + t);
}
}
private static <T> void doSomething(Supplier<T> function, Consumer<T> onOk, Runnable onError) {
T ret = function.get();
if (null != ret) {
onOk.accept(ret);
} else {
onError.run();
}
}
public static void main(String[] args) {
final String[] strings = {"a", "z", "b"};
Arrays.stream(strings).forEach(System.out::println);
final Comparator<String> comparator = (String a, String b) -> a.compareTo(b);
sort(strings, comparator);
Arrays.stream(strings).forEach(System.out::println);
Action2<Integer> action2 = new Action2<>();
doSomething(
() -> 1 + 1,
//(x) -> System.out.println("ok: " + x),
//action2::accept, // (x) -> action2.accept(x),
(x) -> doSomething(() -> 2 + x, null, null),
() -> System.out.println("error")
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment