• Java8新特性


    A lambda expression is an unnamed block of code (or an unnamed function) with a list of formal parameters and a
    body.

    Java8中的lambda表达式不同于C#,使用的是->

    eg:

    // Takes an int parameter and returns the parameter value incremented by 1
    (int x) -> x + 1
    
    // Takes two int parameters and returns their sum
    (int x, int y) -> x + y
    
    // Takes two int parameters and returns the maximum of the two
    (int x, int y) -> { 
        int max = x > y ? x : y;
        return max;
    }
    
    // Takes no parameters and returns void
    () -> { }
    
    // Takes no parameters and returns a string "OK"
    () -> "OK"
    
    // Takes a String parameter and prints it on the standard output
    (String msg) -> { System.out.println(msg); }
    
    // Takes a parameter and prints it on the standard output
    msg -> System.out.println(msg)
    
    // Takes a String parameter and returns its length
    (String str) -> str.length()


    下面看一个简单的例子

    Adder.java

    package corejava2.lambda;
    
    @FunctionalInterface
    public interface Adder {
        double add(double n1, double n2);
    }

    Joiner.java

    package corejava2.lambda;
    
    @FunctionalInterface
    public interface Joiner {
        String join(String s1, String s2);
    }

    TargetTypeTest.java

    package corejava2.lambda;
    
    public class TargetTypeTest {
        public static void main(String[] args) {
            // Creates an Adder using a lambda expression
            Adder adder = (x, y) -> x + y;
            // Creates a Joiner using a lambda expression
            Joiner joiner = (x, y) -> x + y;
            // Adds two doubles
            double sum1 = adder.add(10.34, 89.11);
            // Adds two ints
            double sum2 = adder.add(10, 89);
            // Joins two strings
            String str = joiner.join("Hello", " lambda");
            System.out.println("sum1 = " + sum1);
            System.out.println("sum2 = " + sum2);
            System.out.println("str = " + str);
        }
    }

    运行结果:
    sum1 = 99.45
    sum2 = 99.0
    str = Hello lambda

  • 相关阅读:
    并发编程---守护进程
    并发编程---Process对象的其他属性或方法
    并发编程---开启进程方式---查看进程pid
    并发编程---操作系统
    ie浏览器的css bug
    链接内的图片与文字如何对齐?
    inline元素特性
    最大流EK算法模板
    数据结构 链式表
    运算表达式 栈应用
  • 原文地址:https://www.cnblogs.com/davidgu/p/4857087.html
Copyright © 2020-2023  润新知