您的位置:首页 > 编程语言 > Java开发

Java8的学习计划--lambda表达式的语法

2017-12-25 22:32 477 查看
关于学习JAVA1.8的计划起源于学习Guava ,java1.8 中也算抄袭了很多开源的东西。

java1.8 引入了函数式编程,所以你不必去学习scala等,一样可以写出很优雅的代码。

java1.9 引入的是模块化编程,总之个人看了官网发现,变化最大的还是java1.8.其中的FunctionInterface Streams,spliteror(编写并发执行从代码,多核cpu下执行代码效率大大提高),加上Java1.7的fork-join等结合起来很强大。

开始介绍第一部分关于lambda表达式的语法之前介绍一首歌曲大家



package com.company.LambdaExpressions;

import java.nio.file.DirectoryStream;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.function.*;

/**
* ${DESCRIPTION}
*
* @author mengxp
* @version 1.0
* @create 2017-12-25 21:32
*   parameter list          arrow              lambda body
*    (o1, o2)              ->                o1.getColor().compareTo(o2.getColor());
*
*   valid lambda
*   (String s) -> s.length();
*   (Apple a) -> a.getColor().equals("green");
*   (int x, int y) -> {
*                  int a=x+y;
*                  int b=x*y;
*                  return a+b;};
*    ()->42
**/
public class LambdaFirst {

public static void main(String[] args) {

//1. Comparator 是@FunctionalInterface  没有采用lambda表达式
Comparator<Apple> byColor = new Comparator<Apple>() {
@Override
public int compare(Apple o1, Apple o2) {
return o1.getColor().compareTo(o2.getColor());
}

@Override
public boolean equals(Object obj) {
return false;
}
};
List emptyList = Collections.EMPTY_LIST;
Collections.sort(emptyList,byColor);

//2. 采用lambda表达式 仅仅在这里 在表达式()->{}中存在{},那么需要return关键字,不然可以省略
//反过来存在return关键字必须{}
Comparator<Apple> byColorLambda=(o1, o2) -> {
return o1.getColor().compareTo(o2.getColor());
};
//对于一行搞定的,不需要{},也不需要return关键字
Comparator<Apple> byColorLambdaOneLine=(o1, o2) ->o1.getColor().compareTo(o2.getColor());

//Function 也是@FunctionalInterface  传入一个类型,返回一个类型
Function<String, Integer> consumer = (String s) -> s.length();
//Predicate 也是@FunctionalInterface  传入一个参数 返回一个Boolean
Predicate<Apple> appleFilter = (Apple a) -> a.getColor().equals("green");

Supplier<Apple> appleSupplier=Apple::new;

// IntBinaryOperator 也是@FunctionalInterface
IntBinaryOperator operator = (int x, int y) -> {
int a=x+y;
int b=x*y;
return a+b;
};
MyIntFunctional my=()->45;
MyIntFunctional2 myIntFunctional2=((a, b) -> {
System.out.println(a+b);
System.out.println(a*b);
});

Runnable r=()->{};//定义线程啥都不做

//3.总结lambda表达式的语法
/**
(parameter)->expression;

(parameter)->{ statements};
()->{}  比如定义Runnable
()->"hello"
()->{return "hello"}
(Integer i)->return "hello"+i  invalid 因为存在return 需要{}
*/
}
}




送给大家一句话,考研的同学可能都知道

we are live in the gutter,but some are looking at starts..
To contend or content,this is a problem.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 1.8