亚洲中字慕日产2020,大陆极品少妇内射AAAAAA,无码av大香线蕉伊人久久,久久精品国产亚洲av麻豆网站

資訊專欄INFORMATION COLUMN

Stream流與Lambda表達(dá)式(五) Stream BaseStream AutoClose

HitenDev / 1879人閱讀

摘要:陳楊一流的定義流支持串行并行聚合操作元素序列二流的創(chuàng)建流的創(chuàng)建以方法生成流三

package com.java.design.java8.Stream.StreamDetail;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.stream.Stream;

/**
 * @author 陳楊
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class StreamDetail {

    private List integerList;

    @Before
    public void init() {
        integerList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 0);
    }

    @Test
    public void testStreamDetail() {
一、流的定義
        //    Stream :  A sequence of elements supporting sequential and parallel aggregate operations.
        //    流: 支持 串行、并行 聚合操作 元素序列
二、流的創(chuàng)建
        //    流的創(chuàng)建:
        //    Collection.stream()  Collection.parallelStream()
        //    Stream.generate
        System.out.println("-----------------------------------------
");
        System.out.println("以Stream.generate方法生成流");
        Stream generate = Stream.generate(UUID.randomUUID()::toString);
        generate.findFirst().ifPresent(System.out::println);
        System.out.println("-----------------------------------------
");
三、對(duì)象引用流
        //    對(duì)象引用流
        //    Stream , which is a stream of object references
四、流的計(jì)算
        //    流的計(jì)算:    stream pipeline
        //    To perform a computation, stream operations are composed into a  stream pipeline.
五、流管道組成
        //    流管道組成:  源數(shù)據(jù)source-->數(shù)組、集合、生成器函數(shù)、IO通道等
        //                 [0,n) 中間操作(intermediate operations) 一個(gè)流轉(zhuǎn)換 為 另一個(gè)新流
        //                 終止操作(terminal operation)產(chǎn)生一個(gè)結(jié)果 或有副作用(修改流中元素 屬性或狀態(tài))
        //    A stream pipeline consists of a source (which  might be an array,
        //    a collection, a generator function, an I/O channel,etc),
        //    zero or more intermediate operations (which transform a
        //    stream into another stream, such as {@link Stream#filter(Predicate)}), and a
        //    terminal operation (which produces a result or side-effect, such
        //    as {@link Stream#count()} or {@link Stream#forEach(Consumer)}).
六、流的消費(fèi)
        //    流的消費(fèi):  流中對(duì)于源數(shù)據(jù)的計(jì)算 有且僅有在終止操作觸發(fā)時(shí)才會(huì)被調(diào)用
        //               流中元素只有在被需要時(shí)才會(huì)被消費(fèi)
        //               lazy(惰性): 如果沒有終止操作 那么一系列的中間操作都不會(huì)被執(zhí)行
        //               stream流操作只會(huì)執(zhí)行一次: stream中有一個(gè)容器 將所有中間操作打包 放入容器中
        //               調(diào)用終止操作時(shí) 觸發(fā)容器的鏈?zhǔn)街虚g操作 將流中每一個(gè)元素 應(yīng)用于中間業(yè)務(wù)邏輯
        //    Streams are lazy; computation on the source data is only performed when the
        //    terminal operation is initiated, and source elements are consumed only as needed.
        //    流創(chuàng)建后 只能被消費(fèi)一次 否則拋異常
        //    除非流被設(shè)計(jì)成為顯示并發(fā)修改的流如ConcurrentHashMap 否則未期望或錯(cuò)誤的行為就會(huì)在執(zhí)行時(shí)產(chǎn)生
        //    Unless the source was explicitly designed for concurrent modification
        //    (such as a ConcurrentHashMap),unpredictable or erroneous behavior may result
        //    from modifying the stream source while it is being queried.
        //    java.lang.IllegalStateException: stream has already been operated upon or closed
七、 Lambda表達(dá)式的正確行為
        //    Lambda表達(dá)式的正確行為:
        //    To preserve correct behavior,these behavioral parameters:

        //    must be non-interfering
        //    (they do not modify the stream source);

        //    in most cases must be stateless
        //    (their result should not depend on any state that might change during execution
        //    of the stream pipeline).
八、流與集合
//    流與集合:
//    集合關(guān)注的是對(duì)元素的管理與訪問
//    流不會(huì)直接提供直接訪問或操作其元素的方法
//    流提供聲明性描述: 源 與 建立于源之上的聚合計(jì)算執(zhí)行操作
//    如果流沒有提供預(yù)期的功能 可執(zhí)行受控遍歷(iterator、spliterator)
//    Collections and streams, while bearing some superficial similarities,
//    have different goals.  Collections are primarily concerned with the efficient
//    management of, and access to, their elements.  By contrast, streams do not
//    provide a means to directly access or manipulate their elements, and are
//    instead concerned with declaratively describing their source and the
//    computational operations which will be performed in aggregate on that source.
//    However, if the provided stream operations do not offer the desired
//    functionality, the {@link #iterator()} and {@link #spliterator()} operations
//    can be used to perform a controlled traversal.
九、 流的MapReduce操作
//   流的MapReduce操作  求集合 每個(gè)元素的2倍 之和
//   此例中:Integer 每執(zhí)行一次reduce操作 觸發(fā) 該元素的map操作一次
System.out.println(integerList.stream().map(i -> 2 * i).reduce(0, Integer::sum));
System.out.println("-----------------------------------------
");
十、流資源自動(dòng)關(guān)閉 AutoCloseable接口實(shí)現(xiàn)
package com.java.design.java8.Stream.StreamDetail;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * @author 陳楊
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class AutoCloseableTest implements AutoCloseable {

    /*
     *      An object that may hold resources (such as file or socket handles)
     *      until it is closed. The {@link #close()} method of an {@code AutoCloseable}
     *      object is called automatically when exiting a {@code
     *      try}-with-resources block for which the object has been declared in
     *      the resource specification header. This construction ensures prompt
     *      release, avoiding resource exhaustion exceptions and errors that
     *      may otherwise occur.
     *
     *      實(shí)現(xiàn)AutoCloseable接口:
     *          使用try--with--resources 代碼塊 替代 try--catch--finally
     *          在代碼塊運(yùn)行完畢后 自動(dòng)實(shí)現(xiàn) 資源的關(guān)閉
     *      public interface AutoCloseable {
     *               void close() throws Exception;
     *                }
     */

    public void doSomeThing() {

        System.out.println("method doSomeThing invoked!");
    }


    @Override
    public void close() throws Exception {
        System.out.println("method close invoked!");
    }


    @Test
    public void testAutoCloseable() throws Exception {

        try (AutoCloseableTest autoCloseableTest = new AutoCloseableTest()) {
            autoCloseableTest.doSomeThing();
        }
    }


}
十一、認(rèn)識(shí)BaseStream 與 closeHandler
package com.java.design.java8.Stream.StreamDetail.BaseStreamDetail;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

/**
 * @author 陳楊
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class BaseStreamDetail {

    private List list;
    private NullPointerException myException;

    @Before
    public void init() {
        list = Arrays.asList("Kirito", "Asuna", "Illyasviel", "Sakura");
        myException = new NullPointerException("my NullPointerException");
    }

    @Test
    public void testBaseStreamDetail() {

        // public interface Stream extends BaseStream>

      /*public interface BaseStream> extends AutoCloseable {

         Iterator iterator();

       * Returns a spliterator for the elements of this stream.

         Spliterator spliterator();


       *  當(dāng)終止操作應(yīng)用于流時(shí) 判斷其是否并行
       *  當(dāng)執(zhí)行終止操作之后 執(zhí)行isParallel() 會(huì)得到不可預(yù)期的結(jié)果
       *    此方法需適用于終止操作之前
       *
       * Returns whether this stream, if a terminal operation were to be executed,
       * would execute in parallel.  Calling this method after invoking an
       * terminal stream operation method may yield unpredictable results.
       *
           boolean isParallel();


       * 返回一個(gè)等價(jià)的串行流
       *     流本身已經(jīng)是串行 或 流的狀態(tài)已被修改為串行
       *
       * Returns an equivalent stream that is sequential.  May return
       * itself, either because the stream was already sequential, or because
       * the underlying stream state was modified to be sequential.
       *
        S sequential();


       * 返回一個(gè)等價(jià)的并行流
       *     流本身已經(jīng)是并行 或 流的狀態(tài)已被修改為并行
       *
       * Returns an equivalent stream that is parallel.  May return
       * itself, either because the stream was already parallel, or because
       * the underlying stream state was modified to be parallel.
       *
          S parallel();


       * 返回一個(gè)等價(jià)的無序流
       *     流本身已經(jīng)是無序 或 流的狀態(tài)已被修改為無序
       *
       * Returns an equivalent stream that is
       * unordered.  May return
       * itself, either because the stream was already unordered, or because
       * the underlying stream state was modified to be unordered.
       *
          S unordered();


       * 返回一個(gè)等價(jià)的流 有close handler
       *     close handler當(dāng)流close()方法調(diào)用時(shí)觸發(fā)
       *     調(diào)用順序:close handlers被添加先后順序
       *
       *     所有的close handlers都會(huì)被調(diào)用 即使出現(xiàn)了異常
       *     如果任意close handler拋出異常
       *             那么第一個(gè)異常會(huì)傳遞給調(diào)用段
       *             其他異常(剩余或被抑制)會(huì)傳遞給調(diào)用段
       *                     除非其中有與第一個(gè)異常相同的異常(相同對(duì)象)  因?yàn)橄嗤惓2荒芤种谱陨?       *
       * Returns an equivalent stream with an additional close handler.  Close
       * handlers are run when the {@link #close()} method
       * is called on the stream, and are executed in the order they were
       * added.  All close handlers are run, even if earlier close handlers throw
       * exceptions.  If any close handler throws an exception, the first
       * exception thrown will be relayed to the caller of {@code close()}, with
       * any remaining exceptions added to that exception as suppressed exceptions
       * (unless one of the remaining exceptions is the same exception as the
       * first exception, since an exception cannot suppress itself.)  May
       * return itself.
       *
       * @param closeHandler A task to execute when the stream is closed
       * @return a stream with a handler that is run if the stream is closed

          S onClose(Runnable closeHandler);


       * 關(guān)閉流 調(diào)用流管道中的close handlers
       *
       * Closes this stream, causing all close handlers for this stream pipeline  to be called.

          @Override
          void close();
      }*/


        try (Stream stream = list.stream()) {
            stream.onClose(() -> {
                System.out.println("close handler first");
                // throw new NullPointerException("null pointer exception 1");
                throw myException;
            }).onClose(() -> {
                System.out.println("close handler second");
                // throw new NullPointerException("null pointer exception 2");
                throw myException;
            }).onClose(() -> {
                System.out.println("close handler third");
                // throw new NullPointerException("null pointer exception 3");
                throw myException;
            }).forEach(System.out::println);
        }


    }


}
十二、測(cè)試結(jié)果
testStreamDetail測(cè)試
  .   ____          _            __ _ _
 / / ___"_ __ _ _(_)_ __  __ _    
( ( )\___ | "_ | "_| | "_ / _` |    
 /  ___)| |_)| | | | | || (_| |  ) ) ) )
  "  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.2.RELEASE)

2019-02-20 17:40:31.060  INFO 15872 --- [           main] c.j.d.j.S.StreamDetail.StreamDetail      : Starting StreamDetail on DESKTOP-87RMBG4 with PID 15872 (started by 46250 in E:IdeaProjectsdesign)
2019-02-20 17:40:31.062  INFO 15872 --- [           main] c.j.d.j.S.StreamDetail.StreamDetail      : No active profile set, falling back to default profiles: default
2019-02-20 17:40:31.584  INFO 15872 --- [           main] c.j.d.j.S.StreamDetail.StreamDetail      : Started StreamDetail in 0.728 seconds (JVM running for 1.461)
-----------------------------------------

以Stream.generate方法生成流
2742c0e9-7bdb-4c7e-88c9-b5d94684215c
-----------------------------------------

90
-----------------------------------------
AutoCloseableTest測(cè)試
  .   ____          _            __ _ _
 / / ___"_ __ _ _(_)_ __  __ _    
( ( )\___ | "_ | "_| | "_ / _` |    
 /  ___)| |_)| | | | | || (_| |  ) ) ) )
  "  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.2.RELEASE)

2019-02-20 17:39:45.456  INFO 16320 --- [           main] c.j.d.j.S.S.AutoCloseableTest            : Starting AutoCloseableTest on DESKTOP-87RMBG4 with PID 16320 (started by 46250 in E:IdeaProjectsdesign)
2019-02-20 17:39:45.457  INFO 16320 --- [           main] c.j.d.j.S.S.AutoCloseableTest            : No active profile set, falling back to default profiles: default
2019-02-20 17:39:45.956  INFO 16320 --- [           main] c.j.d.j.S.S.AutoCloseableTest            : Started AutoCloseableTest in 0.716 seconds (JVM running for 1.433)
method doSomeThing invoked!
method close invoked!
testBaseStreamDetail測(cè)試
  .   ____          _            __ _ _
 / / ___"_ __ _ _(_)_ __  __ _    
( ( )\___ | "_ | "_| | "_ / _` |    
 /  ___)| |_)| | | | | || (_| |  ) ) ) )
  "  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.2.RELEASE)

2019-02-20 17:46:41.886  INFO 15216 --- [           main] c.j.d.j.S.S.B.BaseStreamDetail           : Starting BaseStreamDetail on DESKTOP-87RMBG4 with PID 15216 (started by 46250 in E:IdeaProjectsdesign)
2019-02-20 17:46:41.887  INFO 15216 --- [           main] c.j.d.j.S.S.B.BaseStreamDetail           : No active profile set, falling back to default profiles: default
2019-02-20 17:46:42.435  INFO 15216 --- [           main] c.j.d.j.S.S.B.BaseStreamDetail           : Started BaseStreamDetail in 0.762 seconds (JVM running for 1.48)
Kirito
Asuna
Illyasviel
Sakura
close handler first
close handler second
close handler third

java.lang.NullPointerException: my NullPointerException

Process finished with exit code -1


文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請(qǐng)注明本文地址:http://www.ezyhdfw.cn/yun/73346.html

相關(guān)文章

  • Stream流與Lambda達(dá)式(一) 雜談

    摘要:一流轉(zhuǎn)換為數(shù)組集合陳楊將流轉(zhuǎn)換為數(shù)組將流轉(zhuǎn)換為數(shù)組將流轉(zhuǎn)換為集合將流轉(zhuǎn)換為集合解析 一、流 轉(zhuǎn)換為數(shù)組、集合 package com.java.design.java8.Stream; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context...

    Harpsichord1207 評(píng)論0 收藏0
  • Stream流與Lambda達(dá)式(六) SpliteratorDetail

    摘要:陳楊一流的創(chuàng)建源集合一流的創(chuàng)建源集合集合默認(rèn)方法接口與靜態(tài)類實(shí)現(xiàn)接口與靜態(tài)類實(shí)現(xiàn)二接口二接口接口對(duì)數(shù)據(jù)源中元素進(jìn)行遍歷或分區(qū)延遲綁定數(shù)據(jù)源綁定時(shí)機(jī)首次遍歷切分查詢大小而不是在創(chuàng)建時(shí)非延遲綁定數(shù)據(jù)源綁定時(shí)機(jī)創(chuàng)建時(shí)或的方法首次調(diào)用與 package com.java.design.java8.Stream.StreamDetail.BaseStreamDetail; import or...

    cjie 評(píng)論0 收藏0
  • Stream流與Lambda達(dá)式(三) 靜態(tài)工廠類Collectors

    摘要:陳楊一靜態(tài)工廠類實(shí)現(xiàn)方式一靜態(tài)工廠類實(shí)現(xiàn)方式靜態(tài)工廠類最終由實(shí)現(xiàn)通過實(shí)現(xiàn)通過實(shí)現(xiàn)底層由實(shí)現(xiàn)是的一種具化表現(xiàn)形式使用拼接字符串二靜態(tài)工廠類常用收集器二靜態(tài)工廠類常用收集器返回一個(gè)不可修改的按照相遇的順序返回一個(gè)不可修改的無序返回 /** * @author 陳楊 */ @SpringBootTest @RunWith(SpringRunner.class) public class...

    phodal 評(píng)論0 收藏0
  • Stream流與Lambda達(dá)式(四) 自定義收集器

    摘要:一自定義收集器陳楊將集合轉(zhuǎn)換為集合存放相同元素二自定義收集器陳楊將學(xué)生對(duì)象按照存放從中間容器數(shù)據(jù)類型轉(zhuǎn)換為結(jié)果類型數(shù)據(jù)類型一致若不一致拋出類型轉(zhuǎn)換異常對(duì)中間容器數(shù)據(jù)結(jié)果類型進(jìn)行強(qiáng)制類型轉(zhuǎn)換多個(gè)線程同時(shí)操作同一個(gè)容器并行多線 一、自定義SetCustomCollector收集器 package com.java.design.Stream.CustomCollector; impor...

    wind5o 評(píng)論0 收藏0
  • Stream流與Lambda達(dá)式(二) Stream收集器 Collector接口

    摘要:一收集器接口陳楊收集器接口匯聚操作的元素類型即流中元素類型匯聚操作的可變累積類型匯聚操作的結(jié)果類型接口一種可變匯聚操作將輸入元素累積到可變結(jié)果容器中在處理完所有輸入元素后可以選擇將累積的結(jié)果轉(zhuǎn)換為最終表示可選操作歸約操作 一、Stream收集器 Collector接口 package com.java.design.java8.Stream; import com.java.desi...

    or0fun 評(píng)論0 收藏0

發(fā)表評(píng)論

0條評(píng)論

最新活動(dòng)
閱讀需要支付1元查看
<