Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save adityachaudhari/48c701cd9a222e7295d86ef1cef6a623 to your computer and use it in GitHub Desktop.
Save adityachaudhari/48c701cd9a222e7295d86ef1cef6a623 to your computer and use it in GitHub Desktop.
Functional interfaces understanding
package com.java8.functionalinterfaces;
import java.util.function.*;
public class FunctionalInterfacesUnderstandingJava8 {
public static void main(String[] args) {
// take one argument and returns boolean. method declaration : boolean test(T t);
Predicate<String> stringLengthCheckPredicate = (str) -> str.length() < 5;
System.out.println("Predicate returns a boolean. Is string len greater than 5 ? string is : ThisIsTestString " + stringLengthCheckPredicate.test("ThisIsTestString"));
// accept one argument and returns nothing. Method declaration : void accept(T t)
Consumer<String> consumerStr = (str) -> System.out.println(str);
consumerStr.accept("Do some logging work using this consumer which does not returns anything");
// accepts one argument and produces a result. method declaration : R apply(T t);
Function<String, Integer> getLowerCaseStringFunction = (str) -> str.length();
System.out.println("Function check : get string length : " + getLowerCaseStringFunction.apply("what is length of this string"));
// accepts no argument and produces a result. method declaration is : T get();
Supplier<String> supplierProducesString = () -> "this is returned from supplier";
System.out.println("The string returns from supplier without any argument provided : " + supplierProducesString.get());
// accepts two inputs of same type and returns same return type ,method declaration is : T apply(T, T).
BinaryOperator<Integer> binaryOperatorAddition = (a, b) -> a + b;
System.out.println("Binary operator check addition of two numbers : " + binaryOperatorAddition.apply(10, 15));
// accept one argument and returns a result with same like argument return type , method declaration is T apply(T)
UnaryOperator<Integer> unaryOperatorMultiplication = (a) -> a * a;
System.out.println("Unary operator accept one argument and return same type of argument : " + unaryOperatorMultiplication.apply(10));
// BiFunction takes two objects of any type and returns object of any type. method declaration is : R apply(T t, U u);
BiFunction<String, String, Integer> biFunctionStringConcateAndCheckLength = (str1, str2) -> str1.concat(str2).length();
System.out.println("BiFunction takes two argument of any type and return object of any type here taking two Strings concat them and returning total length of them together " + biFunctionStringConcateAndCheckLength.apply("AAA", "BGBG"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment