JAVA8学习——深入浅出Lambda表达式(学习过程)

lambda表达式:

我们为什么要用lambda表达式

  • 在JAVA中,我们无法将函数作为参数传递给一个方法,也无法声明返回一个函数的方法。
  • 在JavaScript中,函数参数是一个函数,返回值是另一个函数的情况下非常常见的,JavaScript是一门非常典型的函数式编程语言,面向对象的语言
//如,JS中的函数作为参数
a.execute(callback(event){
event...
})

Java匿名内部类实例

后面补充一个匿名内部类的代码实例

我这里Gradle的使用来构建项目

需要自行补充对Gradle的学习

Gradle完全可以使用Maven的所有能力

Maven基于XML的配置文件,Gradle是基于编程式配置.Gradle文件

自定义匿名内部类

public class SwingTest {
public static void main(String[] args) {
JFrame jFrame = new JFrame("my Frame");
JButton jButton = new JButton("My Button");
jButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
System.out.println("Button Pressed");
}
});
jFrame.add(jButton);
jFrame.pack();
jFrame.setVisible(true);
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

改造前:

jButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
System.out.println("Button Pressed");
}
});

改造后:

jButton.addActionListener(actionEvent -> System.out.println("Button Pressed"));

Lambda表达式的基本结构

会有自动推断参数类型的功能

(pram1,pram2,pram3)->{

}

函数式接口

概念后期补(接口文档源码,注解源码)
抽象方法,抽象接口
1个接口里面只有一个抽象方法,可以有几个具体的方法 /**
* An informative annotation type used to indicate that an interface
* type declaration is intended to be a <i>functional interface</i> as
* defined by the Java Language Specification.
*
* Conceptually, a functional interface has exactly one abstract
* method. Since {@linkplain java.lang.reflect.Method#isDefault()
* default methods} have an implementation, they are not abstract. If
* an interface declares an abstract method overriding one of the
* public methods of {@code java.lang.Object}, that also does
* <em>not</em> count toward the interface's abstract method count
* since any implementation of the interface will have an
* implementation from {@code java.lang.Object} or elsewhere.
*
* <p>Note that instances of functional interfaces can be created with
* lambda expressions, method references, or constructor references.
*
* <p>If a type is annotated with this annotation type, compilers are
* required to generate an error message unless:
*
* <ul>
* <li> The type is an interface type and not an annotation type, enum, or class.
* <li> The annotated type satisfies the requirements of a functional interface.
* </ul>
*
* <p>However, the compiler will treat any interface meeting the
* definition of a functional interface as a functional interface
* regardless of whether or not a {@code FunctionalInterface}
* annotation is present on the interface declaration.
*
* @jls 4.3.2. The Class Object
* @jls 9.8 Functional Interfaces
* @jls 9.4.3 Interface Method Body
* @since 1.8
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface FunctionalInterface {} 关于函数式接口:
1.如何一个接口只有一个抽象方法,那么这个接口就是函数式接口
2.如果我们在某个接口上生命了FunctionalInterface注解,那么编译器就会按照函数式接口的定义来要求该注解
3.如果某个接口只有一个抽象方法,但我们没有给该接口生命FunctionalInterface接口,编译器也还会把该接口当做成一个函数是接口。(英文最后一段)

通过对实例对函数式接口深入理解


@FunctionalInterface
public interface MyInterface {
void test();
} 错
@FunctionalInterface
public interface MyInterface {
void test(); String tostring1();
} 对 (tostring为重写Object类的方法)
@FunctionalInterface
public interface MyInterface {
void test(); String toString();
}

升级扩展,使用lambda表达式

@FunctionalInterface
interface MyInterface {
void test(); String toString();
} public class Test2{
public void myTest(MyInterface myInterface){
System.out.println("1");
myInterface.test();
System.out.println("2");
} public static void main(String[] args) {
Test2 test2 = new Test2();
//1.默认调用接口里面的接口函数。默认调用MyTest接口里面的test方法。
//2.如果没有参数传入方法,那么可以直接使用()来表达,如下所示
test2.myTest(()-> System.out.println("mytest")); MyInterface myInterface = () -> {
System.out.println("hello");
}; System.out.println(myInterface.getClass()); //查看这个类
System.out.println(myInterface.getClass().getSuperclass());//查看类的父类
System.out.println(myInterface.getClass().getInterfaces()[0]);// 查看此类实现的接口
}
}

默认方法:接口里面,从1.8开始,也可以拥有方法实现了。

默认方法既保证了新特性的添加,又保证了老版本的兼容

//如,Iterable 中的 forEach方法
public interface Iterable<T> {
default void forEach(Consumer<? super T> action) {
Objects.requireNonNull(action);
for (T t : this) {
action.accept(t);
}
}
}

ForEach方法详解

比较重要的是行为,//action行为,而不是数据


/**
* Performs the given action for each element of the {@code Iterable}
* until all elements have been processed or the action throws an
* exception. Unless otherwise specified by the implementing class,
* actions are performed in the order of iteration (if an iteration order
* is specified). Exceptions thrown by the action are relayed to the
* caller.
*
* @implSpec
* <p>The default implementation behaves as if:
* <pre>{@code
* for (T t : this)
* action.accept(t);
* }</pre>
*
* @param action The action to be performed for each element
* @throws NullPointerException if the specified action is null
* @since 1.8
*/
default void forEach(Consumer<? super T> action) {
Objects.requireNonNull(action);
for (T t : this) {
action.accept(t);
}
}

Consumer 类型详解

名字的由来:消费,只消费,没有返回值

/**
* Represents an operation that accepts a single input argument and returns no
* result. Unlike most other functional interfaces, {@code Consumer} is expected
* to operate via side-effects.//接口本身是带有副作用的,会对传入的唯一参数进行修改
*
* <p>This is a <a href="package-summary.html">functional interface</a>
* whose functional method is {@link #accept(Object)}.
*
* @param <T> the type of the input to the operation
*
* @since 1.8
*/
@FunctionalInterface
public interface Consumer<T> { /**
* Performs this operation on the given argument.
*
* @param t the input argument
*/
void accept(T t); /**
* Returns a composed {@code Consumer} that performs, in sequence, this
* operation followed by the {@code after} operation. If performing either
* operation throws an exception, it is relayed to the caller of the
* composed operation. If performing this operation throws an exception,
* the {@code after} operation will not be performed.
*
* @param after the operation to perform after this operation
* @return a composed {@code Consumer} that performs in sequence this
* operation followed by the {@code after} operation
* @throws NullPointerException if {@code after} is null
*/
default Consumer<T> andThen(Consumer<? super T> after) {
Objects.requireNonNull(after);
return (T t) -> { accept(t); after.accept(t); };
}
}

Lambda表达式的作用

  • Lambda表达式为JAVA添加了缺失的函数式编程特性,使我们能够将函数当做一等公民看待
  • 在将函数作为一等公民的语言中,Lambda表达式的类型是函数,但是在JAVA语言中,lambda表达式是一个对象,他们必须依附于一类特别的对象类型——函数是接口(function interface)

迭代方式(三种)

外部迭代:(之前使用的迭代集合的方式,fori这种的)

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8);
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}

内部迭代: ForEach(完全通过集合的本身,通过函数式接口拿出来使用Customer的Accept来完成内部迭代)

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8);
list.forEach(i -> System.out.println(i));

第三种方式:方法引用(method reference)

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8);
list.forEach(System.out::println);

之前的知识只是lambda表达式的入门,后面的学习并没有你想象的那么简单。

解释为什么JAVA中的lambda表达式是一个对象

//解释一下,JAVA的lambda的类型是一个对象
public class Test3 {
public static void main(String[] args) { //函数式接口的实现 1.lambda方式 ()方法的参数 {}方法的实现
TheInterface i1 = () -> {};
System.out.println(i1.getClass().getInterfaces()[0]); TheInterface2 i2 = () -> {};
System.out.println(i2.getClass().getInterfaces()[0]); //必须要通过上下文,来完成类型的推断。上面的lambda是推断出来的,下面这种就是有问题的。
//() -> {}; //通过lambda实现一个线程。 //Runnable runnable;源码里面已经更改为 函数式接口
new Thread(()->{
System.out.println("hello world");
}).start(); //传统方式,转换大写, 遍历,转换,输出
List<String> list = Arrays.asList("hello","worild","hello world");
list.forEach(item ->{
System.out.println(item.toUpperCase());
}); //把list 转换成大写,放入list1 ,然后输出
List<String> list1 = new ArrayList<>(); //diamond语法 类型推断带来的好处
list.forEach(item -> list1.add(item.toUpperCase()));
list1.forEach(System.out::println); //新的方式,采用流的方式去编写。 流与lambda表达式,集合,密切相关。 先体验一下流带来的便利性
// list.stream().map(item -> item.toUpperCase()).forEach(item-> System.out.println(item.toUpperCase()));
list.stream().map(String::toUpperCase).forEach(System.out::println); }
} @FunctionalInterface
interface TheInterface{
void myMethod();
} @FunctionalInterface
interface TheInterface2{
void myMethod2();
}

简单认识一下流

/**
* Returns a sequential {@code Stream} with this collection as its source.
*
* <p>This method should be overridden when the {@link #spliterator()}
* method cannot return a spliterator that is {@code IMMUTABLE},
* {@code CONCURRENT}, or <em>late-binding</em>. (See {@link #spliterator()}
* for details.)
*
* @implSpec
* The default implementation creates a sequential {@code Stream} from the
* collection's {@code Spliterator}.
*
* @return a sequential {@code Stream} over the elements in this collection
* @since 1.8
*/
default Stream<E> stream() {
return StreamSupport.stream(spliterator(), false);
} /**
* Returns a possibly parallel {@code Stream} with this collection as its
* source. It is allowable for this method to return a sequential stream.
*
* <p>This method should be overridden when the {@link #spliterator()}
* method cannot return a spliterator that is {@code IMMUTABLE},
* {@code CONCURRENT}, or <em>late-binding</em>. (See {@link #spliterator()}
* for details.)
*
* @implSpec
* The default implementation creates a parallel {@code Stream} from the
* collection's {@code Spliterator}.
*
* @return a possibly parallel {@code Stream} over the elements in this
* collection
* @since 1.8
*/
default Stream<E> parallelStream() {
return StreamSupport.stream(spliterator(), true);
}

串行流,并行流

中间流,节点流

Pipeline 管道 (Linux的一种实现方式)

流是需要有一个源头的

Lambda表达式作用

  • 传递行为,而不仅仅是值
  • 提升抽象层次
  • API重用性更好
  • 更加灵活

总结

Java Lambda基本语法

  • JAVA中的lambda表达式的基础语法

    • (argument)->{ body }

JAVA lambda结构

  • 一个lambda表达式可以有零个或者多个参数
  • 参数的类型既可以明确声明,也可以根据上下文来推断
  • 所有参数需要包含在圆括号内,参数之间用逗号相隔
  • 空圆括号代表参数集为空
  • 当只有一个参数,且其类型可推导时,圆括号()可以省略。
  • lambda表达式的主体可包含零条或多条语句
  • 如果lambda表达式的主体只有一条语句,花括号{}可以省略。匿名函数的返回类型与该主体表达式一致
  • 如果lambda表达式的主体包含一条以上语句,则表达式必须包含在花括号{}中行成代码块。匿名函数的返回类型与代码块的返回类型一致,若没有返回则为空。

2019年12月29日00:07:05 要睡觉了。笔记后面持续更新,代码会上传到GitHub,欢迎一起学习讨论。

JAVA8学习——深入浅出Lambda表达式(学习过程)的更多相关文章

  1. Java8学习笔记----Lambda表达式 (转)

    Java8学习笔记----Lambda表达式 天锦 2014-03-24 16:43:30 发表于:ATA之家       本文主要记录自己学习Java8的历程,方便大家一起探讨和自己的备忘.因为本人 ...

  2. Java8学习(3)- Lambda 表达式

    猪脚:以下内容参考<Java 8 in Action> 本次学习内容: Lambda 基本模式 环绕执行模式 函数式接口,类型推断 方法引用 Lambda 复合 上一篇Java8学习(2) ...

  3. java8学习之Lambda表达式继续探讨&Function接口详解

    对于上次[http://www.cnblogs.com/webor2006/p/8186039.html]已经初步引入的Java8中Stream流的概念,其中使用了map的操作,它需要接受一个Func ...

  4. java8学习之Lambda表达式深入与流初步

    Lambda表达式深入: 在上一次[http://www.cnblogs.com/webor2006/p/8135873.html]中介绍Lambda表达式的作用时,其中说到这点: 如标红处所说,既然 ...

  5. java8学习之Lambda表达式初步与函数式接口

    对于Java8其实相比之前的的版本增加的内容是相当多的,其中有相当一大块的内容是关于Lambda表达式与Stream API,而这两部分是紧密结合而不能将其拆开来对待的,但是是可以单独使用的,所以从学 ...

  6. JAVA8学习——深入浅出方法引用(学习过程)

    方法引用:method reference 先简单的看一下哪里用到了方法引用: public class MethodReferenceTest { public static void main(S ...

  7. Java8新特性-Lambda表达式是什么?

    目录 前言 匿名内部类 函数式接口 和 Lambda表达式语法 实现函数式接口并使用Lambda表达式: 所以Lambda表达式是什么? 实战应用 总结 前言 Java8新特性-Lambda表达式,好 ...

  8. 乐字节-Java8新特性-Lambda表达式

    上一篇文章我们了解了Java8新特性-接口默认方法,接下来我们聊一聊Java8新特性之Lambda表达式. Lambda表达式(也称为闭包),它允许我们将函数当成参数传递给某个方法,或者把代码本身当作 ...

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

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

随机推荐

  1. bzoj4152 The Captain

    Description 给定平面上的n个点,定义(x1,y1)到(x2,y2)的费用为min(|x1-x2|,|y1-y2|),求从1号点走到n号点的最小费用. Input 第一行包含一个正整数n(2 ...

  2. Entity Framework 映射问题

    今天在数据库(mysql)新增了一个字段,但是一直以为添加字段,然后在实体模型中选择 一直是以为选择"添加",就导致有问题,原因就不说,有点蠢,人家都已经存在,还加上去干嘛,我要的 ...

  3. 大侦探福老师——幽灵Crash谜踪案

    闲鱼Flutter技术的基础设施已基本趋于稳定,就在我们准备松口气的时候,一个Crash却异军突起冲击着我们的稳定性防线!闲鱼技术火速成立侦探小组执行嫌犯侦查行动,经理重重磨难终于在一个隐蔽的角落将其 ...

  4. python的if循环和嵌套

    1.    if 条件:    if语句块   执行流程:判断条件是否为真. 如果真. 执行if语句块 money = int(input('请输入你兜里的钱:')) if money >500 ...

  5. Knative Tracing 介绍

    摘要: 一个完整的业务实现想要基于 Serverless 模型来开发的话可能会分解成多个 Serverless 模块,每一个模块单独通过 Knative 的 Serving 部署,那么这些不同的 Se ...

  6. @hdu - 6428@ Problem C. Calculate

    目录 @description@ @solution@ @accepted code@ @details@ @description@ 给定 A, B, C,求: \[\sum_{i=1}^{A}\s ...

  7. NSOperation 详解

    原文地址:http://nshipster.com/nsoperation/ 大家都知道的秘密是一个应用程序,瞬间响应卸载计算在后台异步完成.因此,现代的Objective-C开发者有两种选择:大中央 ...

  8. linux服务器时间更新

    yum install ntpdate ntpdate ntp1.aliyun.com(阿里云服务器时间)

  9. Android图形子系统

    图形操作可以有两种方式实现:一是利用通用CPU模拟图形操作:二是利用GPU专门做图形操作.前者会增加CPU的负担,在现在高分辨率已经是普遍现象的时候,让通用处理器来完成大量的图形计算已经不现实.And ...

  10. Laravel获取所有的数据库表及结构

    遇到一个需求,需要修改数据库中所有包含email的字段的表,要把里面的长度改为128位.Laravel获取所有的表,然后循环判断表里面有没有email这个字段.代码如下: use Illuminate ...