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,歡迎一起學習討論。