JAVA8学习——深入浅出Lambda表达式(学习过程)
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表达式(学习过程)的更多相关文章
- Java8学习笔记----Lambda表达式 (转)
Java8学习笔记----Lambda表达式 天锦 2014-03-24 16:43:30 发表于:ATA之家 本文主要记录自己学习Java8的历程,方便大家一起探讨和自己的备忘.因为本人 ...
- Java8学习(3)- Lambda 表达式
猪脚:以下内容参考<Java 8 in Action> 本次学习内容: Lambda 基本模式 环绕执行模式 函数式接口,类型推断 方法引用 Lambda 复合 上一篇Java8学习(2) ...
- java8学习之Lambda表达式继续探讨&Function接口详解
对于上次[http://www.cnblogs.com/webor2006/p/8186039.html]已经初步引入的Java8中Stream流的概念,其中使用了map的操作,它需要接受一个Func ...
- java8学习之Lambda表达式深入与流初步
Lambda表达式深入: 在上一次[http://www.cnblogs.com/webor2006/p/8135873.html]中介绍Lambda表达式的作用时,其中说到这点: 如标红处所说,既然 ...
- java8学习之Lambda表达式初步与函数式接口
对于Java8其实相比之前的的版本增加的内容是相当多的,其中有相当一大块的内容是关于Lambda表达式与Stream API,而这两部分是紧密结合而不能将其拆开来对待的,但是是可以单独使用的,所以从学 ...
- JAVA8学习——深入浅出方法引用(学习过程)
方法引用:method reference 先简单的看一下哪里用到了方法引用: public class MethodReferenceTest { public static void main(S ...
- Java8新特性-Lambda表达式是什么?
目录 前言 匿名内部类 函数式接口 和 Lambda表达式语法 实现函数式接口并使用Lambda表达式: 所以Lambda表达式是什么? 实战应用 总结 前言 Java8新特性-Lambda表达式,好 ...
- 乐字节-Java8新特性-Lambda表达式
上一篇文章我们了解了Java8新特性-接口默认方法,接下来我们聊一聊Java8新特性之Lambda表达式. Lambda表达式(也称为闭包),它允许我们将函数当成参数传递给某个方法,或者把代码本身当作 ...
- Java8新特性 - Lambda表达式 - 基本知识
A lambda expression is an unnamed block of code (or an unnamed function) with a list of formal param ...
随机推荐
- 页面头部<meta>中的属性和含义
1<meta name="robots" content="index, follow" /> none:搜索引擎将忽略此网页,等价于noin ...
- Maven启用代理访问
如果你的公司正在建立一个防火墙,并使用HTTP代理服务器来阻止用户直接连接到互联网.如果您使用代理,Maven将无法下载任何依赖. 为了使它工作,你必须声明在 Maven 的配置文件中设置代理服务器: ...
- 从零学React Native之09可触摸组件
可触摸组件有: TouchableHighlight,TouchableNativeFeedback,TouchableOpacity,TouchableWithoutFeedback 1. Touc ...
- idea 使用优化
1.创建类的模板 /** * Copyright (C), 2015-${YEAR}, XXX有限公司 * FileName: ${NAME} * Author: ${USER} * Date: ${ ...
- Android中使用Apache common ftp进行下载文件
版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/birdsaction/article/details/36379201 在Android使用ftp下 ...
- 2018-8-10-WPF-修改按钮按下的颜色
title author date CreateTime categories WPF 修改按钮按下的颜色 lindexi 2018-08-10 19:16:53 +0800 2018-03-15 2 ...
- Python基础:27执行环境
一:可调用对象 可调用对象,是任何能通过函数操作符“()”来调用的对象.Python 有4 种可调用对象:函数,方法,类,以及一些类的实例. 1:函数 python 有 3 种不同类型的函数对象. a ...
- BigData NoSQL —— ApsaraDB HBase数据存储与分析平台概览
一.引言 时间到了2019年,数据库也发展到了一个新的拐点,有三个明显的趋势: 越来越多的数据库会做云原生(CloudNative),会不断利用新的硬件及云本身的优势打造CloudNative数据库, ...
- hdu 2312 Cliff Climbing (pfs)
Problem - 2312 一条很暴力,有点恶心的搜索.题意其实很简单,主要是pfs的时候拓展结点会有种麻烦的感觉.注意的是,这里的n和m跟平常见到的有所不同,交换过来了.我的代码就是在因为这个长宽 ...
- IntelliJ IDEA和Eclipse设置JVM运行参数
打开 IDEA 安装目录,看到有一个 bin 目录,其中有两个 vmoptions 文件,需针对不同的JDK进行配置: 32 位:idea.exe.vmoptions64 位:idea64.exe.v ...