国产xxxx99真实实拍_久久不雅视频_高清韩国a级特黄毛片_嗯老师别我我受不了了小说

資訊專欄INFORMATION COLUMN

Stream流與Lambda表達式(一) 雜談

Harpsichord1207 / 3694人閱讀

摘要:一流轉換為數組集合陳楊將流轉換為數組將流轉換為數組將流轉換為集合將流轉換為集合解析

一、流 轉換為數組、集合
package com.java.design.java8.Stream;

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.ArrayList;
import java.util.List;
import java.util.stream.Stream;

/**
 * @author 陳楊
 */

@SpringBootTest
@RunWith(SpringRunner.class)
public class ListChange {

    private Stream stream = Stream.of("Kirito", "Asuna", "Illyasviel", "Sakura");

    @Test
    public void testListChange() {


        //   將流轉換為數組
        //   System.out.println("-------------將流轉換為數組---------------");
        //   String[] array = stream.toArray(len -> new String[len]);
        //   String[] array = stream.toArray(String[]::new);
        //   Arrays.asList(array).stream().forEach(System.out::println);


        //    將流轉換為集合
        //    System.out.println("-------------將流轉換為集合---------------");
        //    System.out.println("-------Collectors.toList()解析-----------");
        /*    public static 
         *               Collector> toList() {
         *          return new CollectorImpl<>((Supplier>) ArrayList::new, List::add,
         *                 (left, right) -> { left.addAll(right); return left; },
         *                 CH_ID);
        }*/

        //    List list = stream.collect(Collectors.toList());
        //    List linkedList = stream.collect(LinkedList::new,LinkedList::add,LinkedList::addAll);
        List list = stream.collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
        list.forEach(System.out::println);
        System.out.println(list.getClass());


        //    System.out.println("-------Collectors.toCollection()解析-----");

        /*    public static >
         *        Collector toCollection(Supplier collectionFactory) {
         *              return new CollectorImpl<>(collectionFactory, Collection::add,
         *             (r1, r2) -> { r1.addAll(r2); return r1; },
         *              CH_ID);
        }*/

        //    List list =stream.collect(Collectors.toCollection(ArrayList::new));
        //    List linkedList =stream.collect(Collectors.toCollection(ArrayList::new));
        //    Set treeSet =stream.collect(Collectors.toCollection(TreeSet::new));
        //    Set hashSet =stream.collect(Collectors.toCollection(HashSet::new));


    }

}
  .   ____          _            __ _ _
 / / ___"_ __ _ _(_)_ __  __ _    
( ( )\___ | "_ | "_| | "_ / _` |    
 /  ___)| |_)| | | | | || (_| |  ) ) ) )
  "  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.2.RELEASE)

2019-02-20 15:47:22.310  INFO 1348 --- [           main] com.java.design.java8.Stream.ListChange  : Starting ListChange on DESKTOP-87RMBG4 with PID 1348 (started by 46250 in E:IdeaProjectsdesign)
2019-02-20 15:47:22.311  INFO 1348 --- [           main] com.java.design.java8.Stream.ListChange  : No active profile set, falling back to default profiles: default
2019-02-20 15:47:22.947  INFO 1348 --- [           main] com.java.design.java8.Stream.ListChange  : Started ListChange in 0.914 seconds (JVM running for 1.774)
Kirito
Asuna
Illyasviel
Sakura
class java.util.ArrayList
二、集合排序
package com.java.design.java8.Stream;

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.*;

/**
 * @author 陳楊
 */

@SpringBootTest
@RunWith(SpringRunner.class)
public class ComparatorDetail {

    private List names;

    @Before
    public void init() {
        names = Arrays.asList("Kirito", "Asuna", "Sinon", "Yuuki", "Alice");
    }


    public void println() {
        System.out.println(names);
        System.out.println("-----------------------------------------
");
    }

    @Test
    public void testComparatorDetail() {


        //  對名字進行升序排序
        Collections.sort(names);
        this.println();

        //  對名字進行降序排序
        names.sort(Collections.reverseOrder());
        this.println();


        //  按照姓名的字符串長度升序排序 相同長度-->比較前兩個字符-->按照字符的ASCII碼大小升序排序
        names.sort(Comparator.comparingInt(String::length)
                .thenComparing(str -> str.charAt(0))
                .thenComparing(str -> str.charAt(1))
        );
        this.println();


        //  按照姓名的字符串長度降序排序 相同長度-->比較前兩個字符-->按照字符的ASCII碼大小降序排序
        names.sort(Comparator.comparingInt(String::length)
                .thenComparing(str -> str.charAt(0))
                .thenComparing(str -> str.charAt(1))
                .reversed());
        this.println();


        //  按照姓名的字符串長度降序排序 相同長度-->按照字符的ASCII碼大小排序(不區分大小寫)
        names.sort(Comparator.comparingInt(String::length)
                .thenComparing(String.CASE_INSENSITIVE_ORDER));
        this.println();

    }
}
  .   ____          _            __ _ _
 / / ___"_ __ _ _(_)_ __  __ _    
( ( )\___ | "_ | "_| | "_ / _` |    
 /  ___)| |_)| | | | | || (_| |  ) ) ) )
  "  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.2.RELEASE)

2019-02-20 15:58:39.959  INFO 4588 --- [           main] c.j.d.java8.Stream.ComparatorDetail      : Starting ComparatorDetail on DESKTOP-87RMBG4 with PID 4588 (started by 46250 in E:IdeaProjectsdesign)
2019-02-20 15:58:39.962  INFO 4588 --- [           main] c.j.d.java8.Stream.ComparatorDetail      : No active profile set, falling back to default profiles: default
2019-02-20 15:58:40.459  INFO 4588 --- [           main] c.j.d.java8.Stream.ComparatorDetail      : Started ComparatorDetail in 0.729 seconds (JVM running for 1.462)
[Alice, Asuna, Kirito, Sinon, Yuuki]
-----------------------------------------

[Yuuki, Sinon, Kirito, Asuna, Alice]
-----------------------------------------

[Alice, Asuna, Sinon, Yuuki, Kirito]
-----------------------------------------

[Kirito, Yuuki, Sinon, Asuna, Alice]
-----------------------------------------

[Alice, Asuna, Sinon, Yuuki, Kirito]
-----------------------------------------
三、Stream之map(Lambda)
package com.java.design.java8.Stream;

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.Collections;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author 陳楊
 */

@SpringBootTest
@RunWith(SpringRunner.class)
public class StringOperation {

    private List list = Arrays.asList("Kirito", "Asuna", "Illyasviel", "Sakura");

    private List> listMap =
            Arrays.asList(Collections.singletonList("Kirito"), Collections.singletonList("Asuna"),
                    Collections.singletonList("Illyasviel"), Collections.singletonList("Sakura"));

    private List> listFlatMap =
            Arrays.asList(Collections.singletonList("Kirito"), Collections.singletonList("Asuna"),
                    Collections.singletonList("Illyasviel"), Collections.singletonList("Sakura"));


    @Test
    public void testStringOperation() {

        //    集合中 每個字符串  按照排列先后順序拼接 形成一個長字符串
        //    String concat =
        //    list.stream().collect(StringBuilder::new, StringBuilder::append, StringBuilder::append).toString();

        //    String concat = list.stream().collect(Collectors.joining());
        //    System.out.println(concat);


        //    集合中 對每個字符串元素  將所有字母變成大寫字母
        System.out.println("-----------------------------------------
");
        List upperCase = list.stream().map(String::toUpperCase).collect(Collectors.toList());
        upperCase.forEach(System.out::println);


        //    集合中 對每個字符串元素  將所有字母變成小寫字母
        System.out.println("-----------------------------------------
");
        List lowerCase = list.stream().map(String::toLowerCase).collect(Collectors.toList());
        lowerCase.forEach(System.out::println);


        System.out.println("-----------------------------------------
");
        System.out.println("FlatMap與Map的區別:
");

        //    map:  對多個list 分別map Fuction 映射  形成多個list
        System.out.println("-----------------------------------------
");
        System.out.println("進行map映射:");


        List> upperMap = listMap.stream()
                .map(list -> list.stream().map(String::toUpperCase)
                        .collect(Collectors.toList())).collect(Collectors.toList());
        upperMap.forEach(System.out::println);


        //    FlatMap: 對多個list 進行flat扁平化 后再進行map Fuction 映射  形成一個list
        System.out.println("-----------------------------------------
");
        System.out.println("FlatMap扁平化進行map映射:");


        List upperFlatMap = listFlatMap.stream()
                .flatMap(list -> list.stream().map(String::toUpperCase)).collect(Collectors.toList());
        upperFlatMap.forEach(System.out::println);


    }
}
  .   ____          _            __ _ _
 / / ___"_ __ _ _(_)_ __  __ _    
( ( )\___ | "_ | "_| | "_ / _` |    
 /  ___)| |_)| | | | | || (_| |  ) ) ) )
  "  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.2.RELEASE)

2019-02-20 15:50:07.423  INFO 8208 --- [           main] c.j.design.java8.Stream.StringOperation  : Starting StringOperation on DESKTOP-87RMBG4 with PID 8208 (started by 46250 in E:IdeaProjectsdesign)
2019-02-20 15:50:07.424  INFO 8208 --- [           main] c.j.design.java8.Stream.StringOperation  : No active profile set, falling back to default profiles: default
2019-02-20 15:50:07.917  INFO 8208 --- [           main] c.j.design.java8.Stream.StringOperation  : Started StringOperation in 0.717 seconds (JVM running for 1.5)
-----------------------------------------

KIRITO
ASUNA
ILLYASVIEL
SAKURA
-----------------------------------------

kirito
asuna
illyasviel
sakura
-----------------------------------------

FlatMap與Map的區別:

-----------------------------------------

進行map映射:
[KIRITO]
[ASUNA]
[ILLYASVIEL]
[SAKURA]
-----------------------------------------

FlatMap扁平化進行map映射:
KIRITO
ASUNA
ILLYASVIEL
SAKURA
四、內部迭代與外部迭代
package com.java.design.java8.Stream;


import com.java.design.java8.entity.Student;
import com.java.design.java8.entity.Students;
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.*;


/**
 * @author 陳楊
 */

@SpringBootTest
@RunWith(SpringRunner.class)
//迭代本質
public class IterativeEssence {

    private List students;


    @Before
    public void init() {
        students = new Students().init();
    }


    @Test
    public void testIterativeEssence() {

        //    需求: select name from students where  age > 14 and addr ="Sword Art Online"  order by id desc ;


        //    外部迭代
        System.out.println("-----------------------------------------
");
        System.out.println("外部迭代");
        List list = new ArrayList<>();

        for (Student student : students) {
            if (student.getAge() > 14 && student.getAddr().equals("Sword Art Online")) {
                list.add(student);
            }
        }

        list.sort(Comparator.comparingInt(Student::getId));

        for (Student student : list) {
            System.out.println(student.getName());
        }


        //    內部迭代
        System.out.println("-----------------------------------------
");
        System.out.println("內部迭代");
        students.stream()
                .filter(student -> student.getAge() > 14)
                .filter(student -> student.getAddr().equals("Sword Art Online"))
                .sorted(Comparator.comparingInt(Student::getId)).
                forEach(student -> System.out.println(student.getName()));

        //    備注:
        //    內部迭代與SQL語句屬于描述性語言
        //    集合關注的是數據與數據存儲
        //    流關注的是數據的計算
        //    流中間操作返回的都是Stream對象 泛型取決于中間操作的類型
        //    流終止操作: 無返回值(forEach) 返回值是其他類型
    }


}
  .   ____          _            __ _ _
 / / ___"_ __ _ _(_)_ __  __ _    
( ( )\___ | "_ | "_| | "_ / _` |    
 /  ___)| |_)| | | | | || (_| |  ) ) ) )
  "  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.2.RELEASE)

2019-02-20 15:53:03.633  INFO 8864 --- [           main] c.j.d.java8.Stream.IterativeEssence      : Starting IterativeEssence on DESKTOP-87RMBG4 with PID 8864 (started by 46250 in E:IdeaProjectsdesign)
2019-02-20 15:53:03.640  INFO 8864 --- [           main] c.j.d.java8.Stream.IterativeEssence      : No active profile set, falling back to default profiles: default
2019-02-20 15:53:04.167  INFO 8864 --- [           main] c.j.d.java8.Stream.IterativeEssence      : Started IterativeEssence in 0.746 seconds (JVM running for 1.455)
-----------------------------------------

外部迭代
Kirito
Asuna
-----------------------------------------

內部迭代
Kirito
Asuna
五、串行流與并行流 簡單性能測試
package com.java.design.java8.Stream;

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.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;


/**
 * @author 陳楊
 */

@RunWith(SpringRunner.class)
@SpringBootTest
public class ErgodicString {

    private List uuid;
    private long startTime;
    private long endTime;
    private long parallelEndTime;

    @Before
    public void init() {

        uuid = new ArrayList<>(10000000);

        IntStream.range(0, 10000000).forEach(i -> uuid.add(UUID.randomUUID().toString()));

    }


    public void testNormal() {

        startTime = System.nanoTime();
        uuid.stream().sorted().collect(Collectors.toList());

        endTime = System.nanoTime();
        long millis = TimeUnit.NANOSECONDS.toMillis(endTime - startTime);
        System.out.println("單線程" + millis);
    }

    public void testParallel() {

        startTime = System.nanoTime();
        uuid.parallelStream().sorted().collect(Collectors.toList());
        parallelEndTime = System.nanoTime();
        long millis = TimeUnit.NANOSECONDS.toMillis(parallelEndTime - startTime);
        System.out.println("多線程" + millis);
    }


    @Test
    public void testErgodicString() {

        List list = Arrays.asList("Kirito", "Asuna", "Illyasviel", "Sakura");


        //  需求: 將數組中每個元素各個字母大寫 并放入集合

        System.out.println("--------------------串行流stream---------------------");
        // spliterator 分割迭代器
        //  串行流stream() 單線程處理
        /*
         *  default Stream stream() {
         *       return StreamSupport.stream(spliterator(), false);}
         */

        //  List collect = list.stream().map(str -> str.toUpperCase()).collect(Collectors.toList());

        //  R apply(T t); toUpperCase() 沒有參數作為輸入
        //  但把調用toUpperCase的對象作為T作為輸入 返回的R是return的對象結果
        //  List collect = list.stream().map(String::toUpperCase).collect(Collectors.toList());

        Function function = String::toUpperCase;


        //等價于 (String str)  -> str.toUpperCase()
        //方法引用 類的類型::實例方法 對應的lambda表達式 第一個輸入參數 是調用此方法的對象
        List collect = list.stream().map(function).collect(Collectors.toList());

        collect.forEach(System.out::println);

        this.testNormal();

        System.out.println("-----------------并行流parallelStream------------------");
        //  并行流parallelStream() 多線程處理
        /*
         *  default Stream parallelStream() {
         *       return StreamSupport.stream(spliterator(), true);}
         */

        List parallelCollect = list.parallelStream().map(str -> str.toUpperCase()).collect(Collectors.toList());
        parallelCollect.forEach(System.out::println);

        this.testParallel();

    }


}
  .   ____          _            __ _ _
 / / ___"_ __ _ _(_)_ __  __ _    
( ( )\___ | "_ | "_| | "_ / _` |    
 /  ___)| |_)| | | | | || (_| |  ) ) ) )
  "  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.2.RELEASE)

2019-02-20 15:54:54.321  INFO 7356 --- [           main] c.j.design.java8.Stream.ErgodicString    : Starting ErgodicString on DESKTOP-87RMBG4 with PID 7356 (started by 46250 in E:IdeaProjectsdesign)
2019-02-20 15:54:54.323  INFO 7356 --- [           main] c.j.design.java8.Stream.ErgodicString    : No active profile set, falling back to default profiles: default
2019-02-20 15:54:54.817  INFO 7356 --- [           main] c.j.design.java8.Stream.ErgodicString    : Started ErgodicString in 0.705 seconds (JVM running for 1.528)
--------------------串行流stream---------------------
KIRITO
ASUNA
ILLYASVIEL
SAKURA
單線程10590
-----------------并行流parallelStream------------------
KIRITO
ASUNA
ILLYASVIEL
SAKURA
多線程3313

文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。

轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/73353.html

相關文章

  • Stream流與Lambda達式(六) SpliteratorDetail

    摘要:陳楊一流的創建源集合一流的創建源集合集合默認方法接口與靜態類實現接口與靜態類實現二接口二接口接口對數據源中元素進行遍歷或分區延遲綁定數據源綁定時機首次遍歷切分查詢大小而不是在創建時非延遲綁定數據源綁定時機創建時或的方法首次調用與 package com.java.design.java8.Stream.StreamDetail.BaseStreamDetail; import or...

    cjie 評論0 收藏0
  • Stream流與Lambda達式(三) 靜態工廠類Collectors

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

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

    摘要:一自定義收集器陳楊將集合轉換為集合存放相同元素二自定義收集器陳楊將學生對象按照存放從中間容器數據類型轉換為結果類型數據類型一致若不一致拋出類型轉換異常對中間容器數據結果類型進行強制類型轉換多個線程同時操作同一個容器并行多線 一、自定義SetCustomCollector收集器 package com.java.design.Stream.CustomCollector; impor...

    wind5o 評論0 收藏0
  • Stream流與Lambda達式(五) Stream BaseStream AutoClose

    摘要:陳楊一流的定義流支持串行并行聚合操作元素序列二流的創建流的創建以方法生成流三 package com.java.design.java8.Stream.StreamDetail; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframe...

    HitenDev 評論0 收藏0
  • Stream流與Lambda達式(二) Stream收集器 Collector接口

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

    or0fun 評論0 收藏0

發表評論

0條評論

最新活動
閱讀需要支付1元查看
<