package koray.study.lambdas;
import java.util.Arrays;
import java.util.List;
/**
* Created by koray2 on 6/27/16.
*/
public class LambdaDemo {
/**
* Lambdas are backed by single abstract method interfaces.
* They can be used anywhere single method interfaces are required.
* @return
*/
private List<Integer> numbers = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
private void simpleLambdaSyntax() {
Thread th = new Thread(() -> System.out.println("Hello World") );
th.start();
System.out.println("main continues.");
}
private void lambdaForEachExample() {
List<Integer> numbers = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
//foreach method takes a consumer which takes single input
//type of the input can be specified
numbers.forEach( (Integer n ) -> System.out.print( n +" " ) );
System.out.println();
// but it is legally inferred too
numbers.forEach( ( n ) -> System.out.print(n+" " ) );
System.out.println();
//since all lambda does is to pass n to print function
//it can be replaced with the syntax below
numbers.forEach(System.out::println);
}
private void streamExample(){
numbers.stream() //creating a stream of integers
.map(String::valueOf)//take each and turn into String
.map((s)-> s+" ") //append space at end of each element
.forEach(System.out::print);//finally print.
System.out.println();
//shorter version would be
numbers.stream()
.map(e->e.toString()+" ") // get string value and append space and assig it tor return value
.forEach(System.out::print);// input to this function is always string
}
private void streamExampleMultipleParameters(){
int sum = numbers.stream() //creating a stream of integers
.reduce(0 , Integer::sum);//take each and turn into String
System.out.print(sum);
}
/**
* Don't implement logic in lambdas, they should be glue code only. They should be single line.
*
* @param args
*/
public static void main(String ... args){
LambdaDemo demo = new LambdaDemo();
// demo.simpleLambdaSyntax();
// demo.lambdaForEachExample();
// demo.streamExample();
demo.streamExampleMultipleParameters();
}
}