Java 8 新特性:3-函數(Function)介面

來源:互聯網
上載者:User

標籤:height   msu   media   create   less   string   st3   大寫   font   

(原)

以前,在建立泛型時,是這麼寫的:

List<String> list =  new  ArrayList<String>();

現在,可以這麼寫了:

List<String> list = new ArrayList<>();

在java8中,這種寫法被叫作diamond文法,有些書裡叫他鑽石文法,有些則稱之為菱形文法,說的就是這種文法。

 

看下面的例子:

package com.demo.jdk8;import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.function.Function;public class Test3 {public static void main(String[] args) {List<String> list = Arrays.asList("a","b","hello");list.stream().map(i -> i.toUpperCase()).forEach(i -> System.out.println(i));System.out.println("--------------------");list.stream().map(String::toUpperCase).forEach(i -> System.out.println(i));System.out.println("--------------------");Function<String , String> fun = String::toUpperCase;System.out.println(fun.apply("hello"));}} 

Java8裡面,List上層Collection介面中,加入了一個stream方法 

/**     * 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}.     *這個預設的實現會從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);}

stream方法會返回一個串列流,parallelStream方法會返回一個並行流,在這個例子中,你可以將它看作返回了一個Stream,這個Stream是java8新加的介面,其中有一個map方法。 

/**     * Returns a stream consisting of the results of applying the given     * function to the elements of this stream.     *返回一個流,其中包含將給定函數應用到該流的元素的結果。     * <p>This is an <a href="package-summary.html#StreamOps">intermediate     * operation</a>.     *這是一個中間操作     * @param <R> The element type of the new stream         * 返回一個新的流     * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>,     *               <a href="package-summary.html#Statelessness">stateless</a>     *               function to apply to each element     * @return the new stream     */    <R> Stream<R> map(Function<? super T, ? extends R> mapper);

這裡的map接收一個參數,是一個Function介面

@FunctionalInterfacepublic interface Function<T, R>這是一個函數式介面,其中有一個抽象方法。/**     * Applies this function to the given argument.     * 將這個參數運用到給定的參數上     * @param t the function argument     * @return the function result     */    R apply(T t);

  這個方法的含義是接收一個流的參數,返回一個新的流。

在剛才的這個例子中list.stream().map(i -> i.toUpperCase()).forEach(i -> System.out.println(i));

list.stream()先將list轉換成了stream,map是對Function介面的lambda實現,接收了每次迭代的一個參數,然後將該參數轉換成大寫再返回。

i -> i.toUpperCase()這裡的i指的就是R apply(T t);這裡的T,而i.toUpperCase()則是它的返回結果R,那String::toUpperCase這又是什嗎?在java8中,這叫方法的引用,因為toUpperCase並不是static方法,那麼這個字串必需是對象,那麼這個對象是什麼呢?其實這裡的String就是傳入的第一個參數T。這裡總結一下,這個::後面的方法,一定是lambda運算式中第一個參數的方法。因為i -> i.toUpperCase()和String::toUpperCase是等價,這第二種寫法裡,你也可以認為有一個string對象調用了toUpperCase,這個對象是誰呢?就是第一種寫法裡面的i。(這裡確實不太好理解)

在Function中,還有一個靜態方法:

static <T> Function<T, T> identity() {        return t -> t;}

這是在java8中引入的新的寫法。介面中可以有方法的實現,可以是default的,也可以是static的。

Java 8 新特性:3-函數(Function)介面

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.