Java8新特性——從Lambda表示式到Stream流

木子六日發表於2020-12-20

Lambda表示式與Stream

Lambda表示式

基操

首先清楚一個概念,如果一個介面裡面只有一個抽象方法,那麼這個介面就是一個函式式介面。

我們可以使用@FunctionalInterface修飾這個介面,被這個註解修飾的介面如果有多個抽象方法,那麼編譯是不會通過的。

例如:

package com.lambda;
@FunctionalInterface
public interface MyFunctionalInterface {
	void method();
}

假設Demo類中的show方法如下:

package com.lambda;

public class Demo {
	public static void show(MyFunctionalInterface mfi) {
		mfi.method();
	}
}

我們有三種寫法傳遞show方法的引數:

  1. 引數是一個繼承了MyFunctionalInterface的類的物件;
  2. 寫一個匿名內部類,裡面重寫MyFunctionalInterface的抽象方法;
  3. 使用Lambda表示式簡化匿名內部類的寫法;
package com.test;

import org.junit.Test;

import com.lambda.Demo;
import com.lambda.MyFunctionalInterface;

public class TestDemo {

	@Test
	public void testLambda() {
		// 方法1
		// Demo.show(new MyFunctionalInterfaceImpl());

		// 方法2
		Demo.show(new MyFunctionalInterface() {

			@Override
			public void method() {
				System.out.println("這是匿名內部類的寫法");
			}
		});

		// 方法3
		Demo.show(() -> System.out.println("lambda方式的寫法"));
	}
}

這裡舉兩個例子來感受lambda的簡潔:

@Test
public void testThread() {
    //匿名內部類的寫法
    new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName());
        }
    }).start();
    //Lambda寫法
    new Thread(()->System.out.println(Thread.currentThread().getName())).start();
}

@Test
public void testComparator() {
    String[] strs = {"asdfadf","asdfasdfasdf","fasdf","sdfghdsfghshsdfhsdfg"};
    //匿名內部類寫法
    Arrays.sort(strs,new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            return o2.length() - o1.length();
        }
    });
    System.out.println(Arrays.toString(strs));
    //Lambda的寫法
    Arrays.sort(strs,(s1,s2)->s1.length()-s2.length());
    System.out.println(Arrays.toString(strs));
}

方法引用

如果已經有了現成的方法,有些Lambda表示式是不必要寫的,這時候我們就可以把lambda表示式換為方法引用。

舉個例子就知道了。

有如下函式式介面:

package com.lambda;
@FunctionalInterface
public interface Printer {
	void print(String str);
}

有如下方法:

private void p(String s,Printer printer) {
    printer.print(s);
}

方法引用:

@Test
public void testFFYY() {
    p("測試lambda表示式", (s) -> System.out.println(s));
    p("測試方法引用", System.out::println);
}

第一行是使用lambda表示式的方法,但是由於lambda的效果和System.out.println()一樣,我們可以直接使用方法引用。

常見的方法引用有以下幾種:

  • 物件名::成員方法
  • 類名::靜態方法
  • this::成員方法
  • super::成員方法
  • 類名::new (返回該類的物件)
  • 類名[]::new (返回該類的物件陣列)

四種常用的函式式介面

Supplier

用於生產一個指定型別的資料,原始碼如下:

package java.util.function;

@FunctionalInterface
public interface Supplier<T> {

    /**
     * Gets a result.
     *
     * @return a result
     */
    T get();
}

測試案例:

@Test
public void testSupplier() {
    Supplier<String> supplier = () -> "測試supplier";
    System.out.println(supplier.get());
}

Consumer

用於消費一個指定型別的資料,原始碼如下:

package java.util.function;

import java.util.Objects;

@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); };
    }
}

測試案例:

@Test
public void testConsumer() {
    Consumer<String> consumer = (str) -> System.out.println(str);
    consumer.accept("測試consumer");

    consumerAndThen("test andThen in Consumer", 
                    str -> System.out.println(str.toUpperCase()), 
                    str -> System.out.println(str.toLowerCase()));
}

private void consumerAndThen(String str,Consumer<String> c1,Consumer<String> c2) {
    c1.andThen(c2).accept(str);
}

Predicate

用於判斷,返回值為boolean,原始碼如下:

package java.util.function;

import java.util.Objects;

@FunctionalInterface
public interface Predicate<T> {

    /**
     * Evaluates this predicate on the given argument.
     *
     * @param t the input argument
     * @return {@code true} if the input argument matches the predicate,
     * otherwise {@code false}
     */
    boolean test(T t);

    /**
     * Returns a composed predicate that represents a short-circuiting logical
     * AND of this predicate and another.  When evaluating the composed
     * predicate, if this predicate is {@code false}, then the {@code other}
     * predicate is not evaluated.
     *
     * <p>Any exceptions thrown during evaluation of either predicate are relayed
     * to the caller; if evaluation of this predicate throws an exception, the
     * {@code other} predicate will not be evaluated.
     *
     * @param other a predicate that will be logically-ANDed with this
     *              predicate
     * @return a composed predicate that represents the short-circuiting logical
     * AND of this predicate and the {@code other} predicate
     * @throws NullPointerException if other is null
     */
    default Predicate<T> and(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) && other.test(t);
    }

    /**
     * Returns a predicate that represents the logical negation of this
     * predicate.
     *
     * @return a predicate that represents the logical negation of this
     * predicate
     */
    default Predicate<T> negate() {
        return (t) -> !test(t);
    }

    /**
     * Returns a composed predicate that represents a short-circuiting logical
     * OR of this predicate and another.  When evaluating the composed
     * predicate, if this predicate is {@code true}, then the {@code other}
     * predicate is not evaluated.
     *
     * <p>Any exceptions thrown during evaluation of either predicate are relayed
     * to the caller; if evaluation of this predicate throws an exception, the
     * {@code other} predicate will not be evaluated.
     *
     * @param other a predicate that will be logically-ORed with this
     *              predicate
     * @return a composed predicate that represents the short-circuiting logical
     * OR of this predicate and the {@code other} predicate
     * @throws NullPointerException if other is null
     */
    default Predicate<T> or(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) || other.test(t);
    }

    /**
     * Returns a predicate that tests if two arguments are equal according
     * to {@link Objects#equals(Object, Object)}.
     *
     * @param <T> the type of arguments to the predicate
     * @param targetRef the object reference with which to compare for equality,
     *               which may be {@code null}
     * @return a predicate that tests if two arguments are equal according
     * to {@link Objects#equals(Object, Object)}
     */
    static <T> Predicate<T> isEqual(Object targetRef) {
        return (null == targetRef)
                ? Objects::isNull
                : object -> targetRef.equals(object);
    }
}

測試案例:

@Test
public void testPredicate() {
    Predicate<String> predicate = (str) -> str.length() > 5;
    System.out.println(predicate.test("ohhhhhhhh"));
    //還有一些與或非的寫法,不想寫了,感覺沒啥必要
}

Function

用於將一種資料型別轉換為另一種資料型別,原始碼如下:

package java.util.function;

import java.util.Objects;

@FunctionalInterface
public interface Function<T, R> {

    /**
     * Applies this function to the given argument.
     *
     * @param t the function argument
     * @return the function result
     */
    R apply(T t);

    /**
     * Returns a composed function that first applies the {@code before}
     * function to its input, and then applies this function to the result.
     * If evaluation of either function throws an exception, it is relayed to
     * the caller of the composed function.
     *
     * @param <V> the type of input to the {@code before} function, and to the
     *           composed function
     * @param before the function to apply before this function is applied
     * @return a composed function that first applies the {@code before}
     * function and then applies this function
     * @throws NullPointerException if before is null
     *
     * @see #andThen(Function)
     */
    default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
        Objects.requireNonNull(before);
        return (V v) -> apply(before.apply(v));
    }

    /**
     * Returns a composed function that first applies this function to
     * its input, and then applies the {@code after} function to the result.
     * If evaluation of either function throws an exception, it is relayed to
     * the caller of the composed function.
     *
     * @param <V> the type of output of the {@code after} function, and of the
     *           composed function
     * @param after the function to apply after this function is applied
     * @return a composed function that first applies this function and then
     * applies the {@code after} function
     * @throws NullPointerException if after is null
     *
     * @see #compose(Function)
     */
    default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
        Objects.requireNonNull(after);
        return (T t) -> after.apply(apply(t));
    }

    /**
     * Returns a function that always returns its input argument.
     *
     * @param <T> the type of the input and output objects to the function
     * @return a function that always returns its input argument
     */
    static <T> Function<T, T> identity() {
        return t -> t;
    }
}

測試案例:

@Test
public void testFunction() {
    Function<String, Integer> function = (str) -> Integer.valueOf(str) + 10;
    System.out.println(function.apply("23"));
    Function<Integer, String> function2 = (i) -> String.valueOf(i - 20);
    String str = function.andThen(function2).apply("78");
    System.out.println(str);
}

Stream

可分為終結操作和非終結操作,非終結操作完成後仍然返回一個流物件,支援鏈式呼叫。

終結操作主要有foreach和count。

基操

foreach

引數是一個Consumer;

@Test
public void testForEach() {
    List<String> list = new ArrayList<String>();
    list.add("甲");
    list.add("乙");
    list.add("丙");
    list.add("丁");
    list.stream().forEach((item) -> System.out.println(item));
}

filter

引數是一個Predicate;

@Test
public void testFilter() {
    List<String> list = new ArrayList<String>();
    list.add("aaa");
    list.add("asdf");
    list.add("dfsh");
    list.add("asdfasd");
    list.stream().filter(item -> item.length() < 5)
        .filter(item -> item.startsWith("a"))
        .forEach(item -> System.out.println(item));
}

map

引數是一個Function;

@Test
public void testMap() {
    String[] arr = {"17","234","567","16","23","34","345"};
    Stream.of(arr).map(item -> Integer.valueOf(item))
        .filter(item -> item > 40)
        .forEach(item -> System.out.println(item));
}

count

統計個數;

@Test
public void testCount() {
    String[] arr = {"17","234","567","16","23","34","345"};
    long count = Stream.of(arr).map(item -> Integer.valueOf(item))
        .filter(item -> item > 40)
        .count();
    System.out.println(count);
}

limit

取流中前n個物件,引數為n;

@Test
public void testLimit() {
    String[] arr = {"17","234","567","16","23","34","345"};
    Stream.of(arr).limit(4).forEach(item -> System.out.println(item));
}

skip

跳過流中前n個物件,引數為n;

@Test
public void testSkip() {
    String[] arr = {"17","234","567","16","23","34","345"};
    Stream.of(arr).skip(4).forEach(item -> System.out.println(item));
}

concat

將兩個流合併成一個流,引數為兩個流;

@Test
public void testConcat() {
    String[] arr = {"17","234","567","16","23","34","345"};
    List<String> list = new ArrayList<String>();
    list.add("aaa");
    list.add("asdf");
    list.add("dfsh");
    list.add("asdfasd");
    Stream.concat(Stream.of(arr), list.stream()).forEach(item -> System.out.println(item));
}

相關文章