语法例子

		LambdaGrammarTest lambdaTest = new LambdaGrammarTest();

		// 1. 能够推导出类型的,可以不写类型
String[] planets = new String[] { "11", "22", "33" };
Arrays.sort(planets, (first, second) -> first.length() - second.length()); Arrays.sort(planets, String::compareToIgnoreCase); // 2. 删除list中所有的null值, Predicate 接口
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.removeIf(x -> x == null); // 3. BiFunction<T, U, R>
// T - 表示第一个参数, U - 表示第二个参数, R - 表示返回结构result
BiFunction<String, String, Integer> comp = (first, second) -> first.length() - second.length();
System.out.println(comp.apply("11", "222")); java7_biFunction();
java8_biFunction(); // 4. ::
// (1) 对象方法 object::instanceMethod 等同于 x->object.instanceMethod(x);
// (x,y)->object.instanceMethod(x,y);
String string = new String("123456"); MyFunction3 myFunction3 = string::substring;
System.out.println(myFunction3.test(2)); MyFunction4 myFunction4 = string::substring;
System.out.println(myFunction4.test(2, 5)); // (2) 静态方法 Object::staticMethod 等同于 x->Object.staticMethod(x);
// (x,y)->Object.staticMethod(x,y);
MyFunction5 myFunction5 = System.out::println;
myFunction5.test("*******"); MyNumeric2 myNumeric2 = Math::max;
System.out.println(myNumeric2.test(2, 5)); // (3) 对象方法 Object::instanceMethod, 等同于 x,y->x.instanceMethod(y)
Arrays.sort(planets, String::compareToIgnoreCase); MyFunction6 myNumeric6 = string::equalsIgnoreCase;
myNumeric6.test("123456"); MyFunction7 myNumeric7 = String::equalsIgnoreCase;
myNumeric7.test("123456", "123456"); //也可用来调用方法
Person[] personArray = new Person[]{new Person("Tom"),new Person("Jack"),new Person("Alice")}; Arrays.sort(personArray, Comparator.comparing(Person::getName));
for (Person person : personArray) {
System.out.println(person.getName());
} MyFunc<Integer> myClassFunc = MyClass<Integer>::new; //相当于 x -> new MyClass<Integer>(x);
MyClass<Integer> func = myClassFunc.func(100);
System.out.println(func.getVal()); MyFunc2<MyClass<Integer>, Integer> myClassFunc2 = MyClass<Integer>::new;
MyClass<Integer> func2 = myClassFactory(myClassFunc2, 1000);
System.out.println(func2.getVal()); // (4) 使用this
lambdaTest.foo(); // (5) 使用super
new B().foo("Test Super::method"); // (6) 构造器引用 ==>可用来做批量的类型转换
//int[]::new ==> x->new int[x]; ArrayList<String> personStrings = new ArrayList<String>();
personStrings.add("Tom");
personStrings.add("Jack"); //可用来做批量的类型转换, 结合stream & map 用法, 过滤
//得到List
Stream<Person> personStream = personStrings.stream().map(Person::new); //Person::new 相当于 x->new Person(x);调用对应的构造器
List<Person> persons = personStream.collect(Collectors.toList());
for (Person person : persons) {
System.out.println(person.getName());
} //得到数组
personStream = personStrings.stream().map(Person::new);
Person[] personArrays = personStream.toArray(Person[]::new);
for (Person person : personArrays) {
System.out.println(person.getName());
} //5. Lambda表达式中的变量名不能和局部的其它变量名相同 //6. Lambda表达式必须引用值不会改变的变量 //7. 使用Lambda遍历list集合 forEach
personStrings.forEach(n->System.out.println(n)); //8. 其它接口
MyNumber num = () -> 555;
System.out.println(num.getValue()); num = () -> Math.random() * 100;
System.out.println(num.getValue());
System.out.println(num.getValue());
System.out.println(num.getValue()); MyNumeric numic = (n) -> (n % 2) == 0;
System.out.println(numic.test(8)); numic = (n) -> n > 8;
System.out.println(numic.test(8)); MyNumeric2 numic2 = (x, y) -> x * y;
System.out.println(numic2.test(8, 10)); numic2 = (int x, int y) -> x - y;
System.out.println(numic2.test(8, 10)); MyFunction myFunction = (n) -> {
int result = 1; for (int i = 1; i <= n; i++) {
result = result * i;
} return result;
};
System.out.println(myFunction.test(5)); MyFunction2 myFunction2 = (str) -> {
return StringUtils.reverse(str);
};
System.out.println(myFunction2.test("qwert")); SomeFunction<Integer> someFunction1 = (n) -> {
int result = 1; for (int i = 1; i <= n; i++) {
result = result * i;
} return result;
};
System.out.println(someFunction1.test(5)); SomeFunction<String> someFunction2 = (str) -> {
return StringUtils.reverse(str);
};
System.out.println(someFunction2.test("qwert")); String testingStr = "test string";
String test1 = "test1"; String tOperation1 = tOperation((str) -> {
if (StringUtils.isBlank(str)) {
throw new Exception();
} // Local variable test1 defined in an enclosing scope must be final
// or effectively final
// test1=""; return StringUtils.reverse(str + test1);
} , testingStr);
System.out.println(tOperation1); String tOperation2 = tOperation((str) -> str.toUpperCase(), testingStr);
System.out.println(tOperation2); Function<Integer, Integer> factorial = (n) -> {
// ...
return n;
};
System.out.println(factorial.apply(5)); Timer timer = new Timer(1000, xx -> System.out.println(new Date() + "+++++"));
timer.start();
// Thread.slp(1000000); Runnable runnable = ()->{
System.out.println("runnable action 1");
System.out.println("runnable action 2");
System.out.println("runnable action 3");
}; repeat(2, runnable);


辅助方法

	public static void repeat(int n, Runnable action){
for (int i = 0; i < n; i++) {
action.run();
}
} static String tOperation(SomeFunction<String> someFunction, String str) throws Exception {
return someFunction.test(str);
} private static void java7_biFunction() {
BiFunction<String, String, String> bi = new BiFunction<String, String, String>() {
@Override
public String apply(String t, String u) {
return t + u;
}
};
Function<String, String> func = new Function<String, String>() {
@Override
public String apply(String t) {
return t + "-then";
}
};
System.out.println(func.apply("test"));// test-then
System.out.println(bi.apply("java2s.com", "-tutorial"));// java2s.com-tutorial
System.out.println(bi.andThen(func).andThen(func).apply("java2s.com", "-tutorial"));// java2s.com-tutorial-then-then
} private static void java8_biFunction() {
// java8新特性,lambda表达式
BiFunction<String, String, String> bi = (x, y) -> {
return x + y;
};
Function<String, String> func = x -> x + "-then";
System.out.println(func.apply("test"));// test-then
System.out.println(bi.apply("java2s.com", "-tutorial"));// java2s.com
// tutorial
System.out.println(bi.andThen(func).andThen(func).apply("java2s.com", "-tutorial"));// java2s.com-tutorial-then-then
} private void foo(){
MyFunction8 myNumeric8 = this::foo2;
myNumeric8.test("MyFunction8 foo2");
} private void foo2(String x){
System.out.println("foo2-----"+x);
} //Lambda expression's parameter x cannot redeclare another local variable defined in an enclosing scope.
private void foo3(String x){
// MyFunction2 myFunction2 = x->x;
} static <R,T> R myClassFactory(MyFunc2<R, T> cons, T v){
return cons.func(v);
}

函数式接口

interface MyNumber {
double getValue();
} interface MyNumeric {
boolean test(int n);
} interface MyNumeric2 {
int test(int x, int y);
} interface MyFunction {
int test(int n);
} interface MyFunction2 {
String test(String str);
} interface MyFunction3 {
String test(int x);
} interface MyFunction4 {
String test(int x, int y);
} interface MyFunction5 {
void test(String x);
} interface MyFunction6 {
boolean test(String x);
} interface MyFunction7 {
boolean test(String x, String y);
} interface MyFunction8 {
void test(String x);
} interface MyFunction9 extends Runnable{ } interface SomeFunction<T> {
T test(T t) throws Exception;
} class A{
    void foo(String x){
        System.out.println("Parent A foo:"+x);
    }
} class B extends A{
    void foo(String x){
        MyFunction8 xxx = super::foo;
        xxx.test(x);
    }
} interface MyFunc<T>{
    MyClass<T> func(T t);
} interface MyFunc2<R, T>{
    R func(T t);
}
    
class MyClass<T>{
    private T val;
    
    public MyClass() {
        val = null;
    }
    
    public MyClass(T v) {
        val = v;
    }
    
    T getVal(){
        return val;
    }
} class Person{
    public Person() {
        // TODO Auto-generated constructor stub
    }
    
    public Person(String name) {
        this.name=name;
    }
    
    public Person(String name,String firstName,String lastName) {
        this.name=name;
        this.firstName=firstName;
        this.lastName=lastName;
    }
    
    private String name;
    private String firstName;
    private String lastName;     public String getName() {
        return name;
    }     public void setName(String name) {
        this.name = name;
    }     public String getFirstName() {
        return firstName;
    }     public void setFirstName(String firstName) {
        this.firstName = firstName;
    }     public String getLastName() {
        return lastName;
    }     public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

J2SE 8的Lambda --- 语法的更多相关文章

  1. SQL,LINQ,Lambda语法对照图(转载)

    如果你熟悉SQL语句,当使用LINQ时,会有似曾相识的感觉.但又略有不同.下面是SQL和LINQ,Lambda语法对照图 SQL LINQ Lambda SELECT * FROM HumanReso ...

  2. Lisp使用Lambda语法

    lamdba 其实就是一个匿名函数. 定义Lisp的lambda语法非常的简单,如下: (lambda ([parameter]) [experssion]) 调用lambda的语法有三种方法,如下: ...

  3. 初探Lambda表达式/Java多核编程【3】Lambda语法与作用域

    接上一篇:初探Lambda表达式/Java多核编程[2]并行与组合行为 本节是第二章开篇,前一章已经浅显地将所有新概念点到,书中剩下的部分将对这些概念做一个基础知识的补充与深入探讨实践. 本章将介绍L ...

  4. Lambda语法篇

    函数式接口 函数式接口(functional interface 也叫功能性接口,其实是同一个东西).简单来说,函数式接口是只包含一个方法的接口. Lambda语法 包含三个部分 一个括号内用逗号分隔 ...

  5. 通过这些示例快速学习Java lambda语法

    对于那些不熟悉函数式编程的人来说,基本的Java lambda语法起初可能有点令人生畏.但是,一旦将lambda表达式分解为它们的组成部分,语法很快就会变得有意义并变得非常自然. Java中lambd ...

  6. jdk1.8的lambda语法(转)

    原文链接:http://www.jb51.net/article/115081.htm 代码: package com.jdk_8; import org.junit.Test; import jav ...

  7. java1.8学习-什么样的匿名内部类能被lambda语法代替?

    java1.8学习-什么样的匿名内部类能被lambda语法代替? java1.8好多新的特性真的很有意思,特别是Lambda.在学习的时候发现并不是所有的匿名内部类都可以用Lambda代替. lamb ...

  8. C#在属性中用Lambda语法

    今天看代码改功能的时候遇到了个比较奇怪的地方,在属性里也能用Lambda,我看了好久,也不是很理解,我都开始怀疑这是不是属性了,又在群里讨论了下这个问题,觉得有必要记下来,因为又涨知识了. 问题1:这 ...

  9. Lambda 语法

    1.java8 Lambda表达式语法简介 (此处需要使用jdk1.8或其以上版本) Lambd表达式分为左右两侧 * 左侧:Lambda 表达式的参数列表 * 右侧:Lambda 表达式中所需要执行 ...

随机推荐

  1. 产品思维&技术思维&工程思维

    产品思维 产品思维的起源是用户(或客户)价值.用户价值是通过技术手段以产品或服务的形态去解决用户的痛点,或带去爽点.毫无疑问,工程师在日常工作中应时刻关注并理清自己的工作与用户(或客户)价值的联系,并 ...

  2. Angular 4.0 安装组件

    安装组件 ng g componet 组件名

  3. Microsoft Dynamics CRM 2011 中 SQL 语句总结

    一.查询用户和团队 插入的类型:OwnerIdType 可以为用户或团队: 1.团队: select top 1 ObjectTypeCode from metadataschema.entity w ...

  4. DEDECMS ShowMsg()样式修改 提示信息的修改以及美化

    织梦DedeCMS系统,处处都在用到提示信息,但是这个提示框,前台后台一层不变,太死板了,可能有很多人都有过去修改它的想法,只是苦于不知道去哪里 改.今天我就来说说这个吧,DedeCMS的所有提示信息 ...

  5. wxWidgets:入门

    0. 介绍 wxWidgets是一个开源的跨平台的C++构架库(framework),它可以提供GUI和其它工具.目前的3.0.0版本支持所有版本的Windows.带GTK+或Motif的Unix和M ...

  6. ALGO-5_蓝桥杯_算法训练_最短路

    记: 一开始没接触过关于最短距离的算法,便开始翻阅关于图的知识, 得知关于最短距离的算法有Dijkstra算法(堆优化暂未看懂),Bellman-Ford算法,Floyd算法,SPFA算法. 由于数据 ...

  7. pychar入门参考教材

    参考:  http://blog.csdn.net/chenggong2dm/article/category/6137682 让不同py文件运行,直接在文件的标签处右键run即可

  8. GC之五--SystemGC完全解读

    目录: GC之一--GC 的算法分析.垃圾收集器.内存分配策略介绍 GC之二--GC日志分析(jdk1.8)整理中 GC之三--GC 触发Full GC执行的情况及应对策略 gc之四--Minor G ...

  9. 分布式开放消息系统RocketMQ的原理与实践(消息的顺序问题、重复问题、可靠消息/事务消息)

    备注:1.如果您此前未接触过RocketMQ,请先阅读附录部分,以便了解RocketMQ的整体架构和相关术语2.文中的MQServer与Broker表示同一概念 分布式消息系统作为实现分布式系统可扩展 ...

  10. Discuz论坛管理的问题汇总

    Discuz论坛在Linux上搭建成功了, 不得不说, 其功能是非常强大的, 可以满足已知的绝大多数的需求. 搭建完成后也有一些问题, 在这里汇总一下, 以便将来查阅. 1. 显示未处理用户信息, 但 ...