Skip to content

Instantly share code, notes, and snippets.

@ucguy4u
Created September 19, 2020 05:44
Show Gist options
  • Save ucguy4u/351cf6ada9c6de3fbf938eb9882cadbc to your computer and use it in GitHub Desktop.
Save ucguy4u/351cf6ada9c6de3fbf938eb9882cadbc to your computer and use it in GitHub Desktop.
Get the taste of Lambdas
package com.ucguy4u.functional.java;
import java.math.BigInteger;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.function.UnaryOperator;
/**
*
* @author chauhanuday
*/
public class Lambdas_02 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
IntFunction<String> intToString = num -> Integer.toString(num);
System.out.println("expected value 3, actual value: " +
intToString.apply(123).length());
//static method reference using ::
IntFunction<String> intToString2 = Integer::toString;
System.out.println("\nexpected value 4, actual value: " +
intToString2.apply(4567).length());
//lambdas made using a constructor
Function<String,BigInteger> newBigInt = BigInteger::new;
System.out.println("\nexpected value: 123456789, actual value: "+
newBigInt.apply("123456789"));
//example of a lambda made from an instance method
Consumer<String> print = System.out::println;
print.accept("\nComing to you directly from a lambda...");
//these two are the same using the static method concat
UnaryOperator<String> greeting = x -> "Hello, ".concat(x);
System.out.println("\n"+greeting.apply("World"));
UnaryOperator<String> makeGreeting = "Hello, "::concat;
System.out.println("\n"+makeGreeting.apply("Peggy"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment