Created
September 19, 2020 05:44
-
-
Save ucguy4u/351cf6ada9c6de3fbf938eb9882cadbc to your computer and use it in GitHub Desktop.
Get the taste of Lambdas
This file contains hidden or 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
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