Java8

lambda表达式与方法引用

  • lambda表达式
  1. 一般形式:

      (a,b)->a+b;
      (a,b)->{
      statement;
      return value;
      }
    
  2. 变量作用域
    lambda类似于匿名函数,不过lambda表达式没有新的变量作用

import java.util.function.Consumer;

 public class LambdaScopeTest {

  public int x = 0;

  class FirstLevel {

      public int x = 1;

      void methodInFirstLevel(int x) {
          
          // The following statement causes the compiler to generate
          // the error "local variables referenced from a lambda expression
          // must be final or effectively final" in statement A:
          //
          // x = 99;
          
          Consumer<Integer> myConsumer = (y) -> 
          {
              System.out.println("x = " + x); // Statement A
              System.out.println("y = " + y);
              System.out.println("this.x = " + this.x);
              System.out.println("LambdaScopeTest.this.x = " +
                  LambdaScopeTest.this.x);
          };

          myConsumer.accept(x);

      }
  }

  public static void main(String... args) {
      LambdaScopeTest st = new LambdaScopeTest();
      LambdaScopeTest.FirstLevel fl = st.new FirstLevel();
      fl.methodInFirstLevel(23);
  }
}

结果输出:

x = 23
y = 23
this.x = 1
LambdaScopeTest.this.x = 0

如果将上面lambda表达式中的y换为x

        Consumer<Integer> myConsumer = (x) -> {
            // ...
        }

编译器将产生变量已定义的错误

  • 方法引用
种类 Example
静态方法 ContainingClass::staticMethodName
指定对象的实例的方法 containingObject::instanceMethodName
任意对象实例的特定类型的方法 ContainingType::methodName
构造方法 ClassName::new

e.g:

  1. 静态方法:
public class Person {
  ........
    public static int compareByAge(Person a, Person b) {
        return a.birthday.compareTo(b.birthday);
    }}

  Arrays.sort(rosterAsArray, Person::compareByAge);
  1. 对象的实例的方法
class ComparisonProvider {
  public int compareByName(Person a, Person b) {
      return a.getName().compareTo(b.getName());
  }
      
  public int compareByAge(Person a, Person b) {
      return a.getBirthday().compareTo(b.getBirthday());
  }
}
ComparisonProvider myComparisonProvider = new ComparisonProvider();
Arrays.sort(rosterAsArray, myComparisonProvider::compareByName);
  1. 基本类型的发放
String[] stringArray = { "Barbara", "James", "Mary", "John",
  "Patricia", "Robert", "Michael", "Linda" };
Arrays.sort(stringArray, String::compareToIgnoreCase);
  1. 构造方法
public static <T, SOURCE extends Collection<T>, DEST extends 
Collection<T>>
    DEST transferElements(
        SOURCE sourceCollection,
        Supplier<DEST> collectionFactory) {
        DEST result = collectionFactory.get();
        for (T t : sourceCollection) {
             result.add(t);
        }
        return result;
}
/*The functional interface Supplier contains one method get that 
*takes no arguments and returns an object. Consequently, you can 
*invoke the method transferElements with a lambda expression as 
*follows:
*/

Set<Person> rosterSetLambda =
    transferElements(roster, () -> { return new HashSet<>(); });
/*You can use a constructor reference in place of the lambda expression as follows:*/

Set<Person> rosterSet = transferElements(roster, HashSet::new);
/*The Java compiler infers that you want to create a HashSet 
*collection that contains elements of type Person. Alternatively, you 
*can specify this as follows:
*/
Set<Person> rosterSet = transferElements(roster, HashSet<Person>::new);

默认方法

java8 中可以给 使用default 给 interface 添加默认方法,添加的默认方法为 public方法,继承了有默认方法的接口,可以对默认方法做一下操作:

  1. 不理会默认方法,这样子类使用接口中的方法。
  2. 再次声明默认方法,将默认方法变为抽象方法。
  3. overrides 默认方法

接口中还可以使用static 关键字定义静态方法。

聚合操作

java 8新增了java.util.stream包,这个包主要提供了streams 和聚合操作的接口和类
简单的实例:

roster
    .stream()
    .filter(e -> e.getGender() == Person.Sex.MALE)
    .forEach(e -> System.out.println(e.getName()));

一系列的聚合操作被称为pipeline
JDK文档中对pipeline的定义是:pipeline包含一个source,0个或多个中间操作(像filter),和一个终结操作(例子中的forEach())
聚合操作有利于并行计算,可提高CPU使用效率。


参考:Enhancements in Java SE 8

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • lambda表达式(又被成为“闭包”或“匿名方法”)方法引用和构造方法引用扩展的目标类型和类型推导接口中的默认方法...
    183207efd207阅读 1,498评论 0 5
  • 原文地址http://blog.csdn.net/myherux/article/details/52717492...
    Vissioon阅读 398评论 0 0
  • 根据 Android 官网的说明,在开发面向 Android N 的应用时,可以使用 Java8 语言功能。目前 ...
    芭蕾武阅读 1,128评论 0 0
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,754评论 18 399
  • 【专题:玉】 “赌石”,玉器行业里最为考较眼力见识的。其实,赌石赌的不是玉石,是经验是经历是魄力!玉石不会骗人,老...
    南阳雅月阅读 5,058评论 3 4