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,欢迎一起学习讨论。