码迷,mamicode.com
首页 > 编程语言 > 详细

Java8新特性 - Lambda表达式 - 基本知识

时间:2015-10-06 15:19:51      阅读:224      评论:0      收藏:0      [点我收藏+]

标签:

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

 

Java8新特性 - Lambda表达式 - 基本知识

标签:

原文地址:http://www.cnblogs.com/davidgu/p/4857087.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!