Skip to content

Instantly share code, notes, and snippets.

@rolroralra
Last active July 29, 2022 15:14
Show Gist options
  • Save rolroralra/794d86196811d37c2c644af8eab0e425 to your computer and use it in GitHub Desktop.
Save rolroralra/794d86196811d37c2c644af8eab0e425 to your computer and use it in GitHub Desktop.
Lambda, FunctionalInterface

FunctionalInterface (Java 8)

Functional Interface Function Descriptor Specific Interface
Predicate T -> boolean IntPredicate
LongPredicate
DoublePredicate
Consumer T -> void IntConsumer
LongConsumer
DoubleConsumer
Function T -> R IntFunction<R>
IntToLongFunction
IntToDoubleFunction
LongFunction<R>
LongToIntFunction
LongToDoubleFunction
DoubleFunction<R>
DoubleToIntFunction
DoubleToLongFunction
ToIntFunction<T>
ToLongFunction<T>
ToDoubleFunction<T>
Supplier () -> T BooleanSupplier
IntSupplier
LongSupplier
DoubleSupplier
UnaryOperator T -> T IntUnaryOperator
LongUnaryOperator
DoubleUnaryOperator
BinaryOperator (T, T) -> T IntBinaryOperator
LongBinaryOperator
DoubleBinaryOperator
BiPredicate (T, U) -> boolean
BiConsumer (T, U) -> void ObjIntConsumer<T>
ObjLongConsumer<T>
ObjDoubleConsumer<T>
BiFunction (T, U) -> R ToIntBiFunction<T, U>
ToLongBiFunction<T, U>
ToDoubleBiFunction<T, U>

Comparator - comparing, reversed, thenComparing

inventory.sort(Comparator.comparing(Apple:getWeight)
         .reversed()
         .thenComparing(Apple::getCountry));

Predicate - and, or, negate

Predicate<Apple> notRedApple = redApple.negate();

Predicate<Apple> redAndHeavyAppleOrNotGreen = 
  redApple.and(apple -> apple.getWeight() > 150)
          .or(apple -> GREEN.equals(a.getColor()));            

Function - andThen, compose

IntUnaryOperator f = i -> i + 1;
IntUnaryOperator g = i -> i * 3;

System.out.println("f(x) = x + 1");
System.out.println("g(x) = x * 3");
System.out.printf("g(f(2)) = %d\n", f.andThen(g).applyAsInt(2));  // 9
System.out.printf("f(g(2)) = %d\n",f.compose(g).applyAsInt(2));   // 7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment