java 一些使用lambda语法的示例

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 一些使用lambda语法的示例相关的知识,希望对你有一定的参考价值。

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();
    }
    
    
   
}

以上是关于java 一些使用lambda语法的示例的主要内容,如果未能解决你的问题,请参考以下文章

Java 8 lambda表达式20180404

jdk 8 lambda表达式 及在Android Studio的使用示例

Java8新特性Lambda表达式基础语法,都在这儿了!!

Lambda 表达式常用语法

使用 lambda 定义可以带来啥乐趣?

Java Lambda Stream