欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

java8中Stream的使用示例教程

 更新時(shí)間:2018年10月31日 14:43:01   作者:jihite  
Stream是Java8的一大亮點(diǎn),是對容器對象功能的增強(qiáng),下面這篇文章主要給大家介紹了關(guān)于java8中Stream使用的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

前言

Java8中提供了Stream對集合操作作出了極大的簡化,學(xué)習(xí)了Stream之后,我們以后不用使用for循環(huán)就能對集合作出很好的操作。

本文將給大家詳細(xì)介紹關(guān)于java8 Stream使用的相關(guān)內(nèi)容,下面話不多說了,來一起看看詳細(xì)的介紹吧

1. 原理

Stream 不是集合元素,它不是數(shù)據(jù)結(jié)構(gòu)并不保存數(shù)據(jù),它是有關(guān)算法和計(jì)算的,它更像一個(gè)高級版本的 Iterator。

原始版本的 Iterator,用戶只能顯式地一個(gè)一個(gè)遍歷元素并對其執(zhí)行某些操作;

高級版本的 Stream,用戶只要給出需要對其包含的元素執(zhí)行什么操作,比如:

  • 所有元素求和
  • 過濾掉長度大于 10 的字符串
  • 獲取每個(gè)字符串的首字母

Stream 就如同一個(gè)迭代器(Iterator),單向,不可往復(fù),數(shù)據(jù)只能遍歷一次,遍歷過一次后即用盡了,就好比流水從面前流過,一去不復(fù)返。

而和迭代器又不同的是,Stream 可以并行化操作

Stream 的另外一大特點(diǎn)是,數(shù)據(jù)源本身可以是無限的

2.使用步驟

獲取一個(gè)數(shù)據(jù)源(source)→ 數(shù)據(jù)轉(zhuǎn)換→執(zhí)行操作獲取想要的結(jié)果

每次轉(zhuǎn)換原有 Stream 對象不改變,返回一個(gè)新的 Stream對象(可以有多次轉(zhuǎn)換),這就允許對其操作可以像鏈條一樣排列,變成一個(gè)管道,如下圖所示。

3. Stream的構(gòu)造

public void test4() {
 Stream stream = Stream.of("a", "b", "c", 23);
 stream.forEach(key -> System.out.println(key));

 String[] array = new String[]{"abc", "efg"};
 stream = Stream.of(array);
 stream = Arrays.stream(array);
 stream.forEach(key -> System.out.println(key));

 List<String> list = Arrays.asList(array);
 stream = list.stream();

 //IntStream、LongStream、DoubleStream
 IntStream stream2 = IntStream.of(1, 2, 3, 3);
 DoubleStream stream4 = DoubleStream.of(1, 2, 3, 3.4);

 stream2.forEach(key -> System.out.println(key));
 stream4.forEach(key -> System.out.println(key));
 }

結(jié)果

a
b
c
23
abc
efg
1
2
3
3
1.0
2.0
3.0

4. Stream的轉(zhuǎn)換

public void test6() {
 Stream stream = Stream.of("abc", "def");

 String[] array = (String[])stream.toArray(String[]::new);
 System.out.println(array.length);
 List<String> list = (List<String>)Stream.of("1", "2", "3").collect(Collectors.toList());
 String str = Stream.of("abc", "mn").collect(Collectors.joining()).toString();
 System.out.println(array);
 System.out.println(list);
 System.out.println(str);
 }

結(jié)果

2

[Ljava.lang.String;@17f052a3
[1, 2, 3]
abcmn

5.一個(gè) Stream 只可以使用一次

public void test6_5() {
 Stream stream = Stream.of(1, 2, 3, 2);
 System.out.println("count:" + stream.count());
 System.out.println("count:" + stream.count());
} 

輸出

Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed
    at java.util.stream.AbstractPipeline.<init>(AbstractPipeline.java:203)
    at java.util.stream.LongPipeline.<init>(LongPipeline.java:91)
    at java.util.stream.LongPipeline$StatelessOp.<init>(LongPipeline.java:572)
    at java.util.stream.ReferencePipeline$5.<init>(ReferencePipeline.java:221)
    at java.util.stream.ReferencePipeline.mapToLong(ReferencePipeline.java:220)
    at java.util.stream.ReferencePipeline.count(ReferencePipeline.java:526)
    at streamTest.StreamTest.test6_5(StreamTest.java:68)
    at streamTest.StreamTest.main(StreamTest.java:181)
count:4

6.轉(zhuǎn)換大寫

public void test7() {
 List<String> list = Arrays.asList("a", "MnM");

 List<String> result = list.stream().
 map(String::toUpperCase).
 collect(Collectors.toList());
 System.out.println(list);
 System.out.println(result);
 }

輸出

[a, MnM]
[A, MNM]

7.平方

public void test8() {
 List<Integer> list2 = Arrays.asList(1, 2, 4);
 List<Integer> list3 = list2.stream().
 map(key -> key * key).
 collect(Collectors.toList());
 System.out.println(list2);
 System.out.println(list3);

 }

輸出

[1, 2, 4]
[1, 4, 16]

8.找偶數(shù)

public void test8_5() {
 List<Integer> list2 = Arrays.asList(1, 2, 4);
 List<Integer> list3 = list2.stream().
 filter(key -> key % 2 == 0).
 collect(Collectors.toList());
 System.out.println(list2);
 System.out.println(list3);
 }

輸出

[1, 2, 4]
[2, 4]

9. 區(qū)間值

public void test5() {
 System.out.println("\n");
 IntStream.range(1, 3).forEach(System.out::println);
 System.out.println("\n");
 IntStream.rangeClosed(1, 3).forEach(System.out::println);
 }

結(jié)果

1
2
 
 
1
2
3

10.并發(fā)

 public void test5_pa() {
 IntStream.rangeClosed(1, 10).parallel().forEach(System.out::println);
 }

輸出

3
7
1
5
2
8
10
6
9
4  

是否并發(fā)思考

11. 新的Stream繼續(xù)操作

public void test6_6() {
 Stream.of("one", "two", "three", "four")
 .filter(e -> e.length() > 3)
 .peek(e -> System.out.println("Filtered value: " + e))
 .map(String::toUpperCase)
 .peek(e -> System.out.println("Mapped value: " + e))
 .collect(Collectors.toList());
 }

結(jié)果

Filtered value: three
Mapped value: THREE
Filtered value: four
Mapped value: FOUR

12. Optional

public static void print(String text) {
 System.out.println("<<<<<<");
 System.out.println(Optional.ofNullable(text));
 List<String> obj = new ArrayList<>();
 Optional.ofNullable(text).ifPresent(System.out::println);
 System.out.println(">>>>>>>>>>>>\n");
 }
 public static int getLength(String text) {
 return Optional.ofNullable(text).map(String::length).orElse(-1);
 }

 public void test14() {
 String strA = " abcd ", strB = null;
 print(strA);
 print("");
 print(strB);

 System.out.println(getLength(strA));
 System.out.println(getLength(""));
 System.out.println(getLength(strB));
 }

結(jié)果

<<<<<<
Optional[ abcd ]
 abcd
>>>>>>>>>>>>
 
<<<<<<
Optional[]
 
>>>>>>>>>>>>
 
<<<<<<
Optional.empty
>>>>>>>>>>>>
 
6
0
-1

13. 字符串拼接、最值、求和、過濾

public void test15() {
 String concat = Stream.of("A", "B", "C").reduce("", String::concat);
 System.out.println("concat:" + concat);

 double minValue = Stream.of(-1.5, 1.0, -3.0, -2.0).reduce(Double.MAX_VALUE, Double::min);
 System.out.println("min:" + minValue);

 int sumValue = Stream.of(1, 2, 3, 4).reduce(0, Integer::sum);
 System.out.println("sum1:" + sumValue);

 int sumValue2 = Stream.of(1, 2, 3, 4).reduce(Integer::sum).get();
 System.out.println("sum2:" + sumValue2);

 concat = Stream.of("a", "B", "c", "D", "e", "F").filter(x -> x.compareTo("Z") > 0).reduce("", String::concat);
 System.out.println("concat:" + concat);
 }

結(jié)果

concat:ABC
min:-3.0
sum1:10
sum2:10
concat:ace

14. limit, skip

public void test16() {
 List<Person> persons = new ArrayList<>();
 IntStream.range(1, 1000).forEach(key->persons.add(new Person(key, "jihite:" + key)));
 List<String> personList = persons.stream().map(Person::getName).limit(10).skip(3).collect(Collectors.toList());
 System.out.println(personList);
 }

輸出

[jihite:4, jihite:5, jihite:6, jihite:7, jihite:8, jihite:9, jihite:10]

15.找出最長一行的長度

public void test19() throws IOException {
 String path = "**/Person.java";
 BufferedReader br = new BufferedReader(new FileReader(path));
 int longest = br.lines()
 .mapToInt(String::length)
 .max()
 .getAsInt();
 br.close();
 System.out.println(longest);
 }

輸出

16.找出全文的單詞,轉(zhuǎn)小寫,并排序

public void test20() throws IOException {
 String path = "**/Person.java";
 BufferedReader br = new BufferedReader(new FileReader(path));
 List<String> words = br.lines()
 .flatMap(line->Stream.of(line.split(" ")))
 .filter(word->word.length()>0)
 .map(String::toLowerCase)
 .distinct()
 .sorted()
 .collect(Collectors.toList());
 br.close();
 System.out.println(words);
 words.forEach(key-> System.out.println(key));
 }

輸出

*
*/
/**
//
2018/10/24
21:40
=
@author:
@date:
@description:
class
getname()
int
name)

參考

Java 8 中的 Streams API 詳解

總結(jié)

以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。

相關(guān)文章

  • Java線程協(xié)作的兩種方式小結(jié)

    Java線程協(xié)作的兩種方式小結(jié)

    Java中線程協(xié)作的最常見的兩種方式是利用Object.wait()、Object.notify()和使用Condition,本文主要介紹了Java線程協(xié)作的兩種方式小結(jié),文中通過示例代碼介紹的非常詳細(xì),需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-05-05
  • Spring.Net在MVC中實(shí)現(xiàn)注入的原理解析

    Spring.Net在MVC中實(shí)現(xiàn)注入的原理解析

    這篇文章主要介紹了Spring.Net在MVC中實(shí)現(xiàn)注入的原理解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-09-09
  • 別在Java代碼里亂打日志了,這才是正確的打日志姿勢

    別在Java代碼里亂打日志了,這才是正確的打日志姿勢

    這篇文章主要介紹了別在Java代碼里亂打日志了,這才是正確的打日志姿勢,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-06-06
  • java中HashMap.values()轉(zhuǎn)為ArrayList()問題

    java中HashMap.values()轉(zhuǎn)為ArrayList()問題

    這篇文章主要介紹了java中HashMap.values()轉(zhuǎn)為ArrayList()問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-03-03
  • Java9版本新特性同一個(gè)Jar支持多JDK版本運(yùn)行

    Java9版本新特性同一個(gè)Jar支持多JDK版本運(yùn)行

    這篇文章主要為大家介紹了Java9新版本的特性之同一個(gè)Jar支持多JDK版本運(yùn)行的示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步
    2022-03-03
  • 深入淺出Java中重試機(jī)制的多種方式

    深入淺出Java中重試機(jī)制的多種方式

    重試機(jī)制在分布式系統(tǒng)中,或者調(diào)用外部接口中,都是十分重要的。重試機(jī)制可以保護(hù)系統(tǒng)減少因網(wǎng)絡(luò)波動(dòng)、依賴服務(wù)短暫性不可用帶來的影響,讓系統(tǒng)能更穩(wěn)定的運(yùn)行的一種保護(hù)機(jī)制。本文就來和大家聊聊Java中重試機(jī)制的多種方式
    2023-03-03
  • 學(xué)習(xí)Java HashMap,看這篇就夠了

    學(xué)習(xí)Java HashMap,看這篇就夠了

    這篇文章主要介紹了Java HashMap的相關(guān)資料,文中示例代碼非常詳細(xì),幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下
    2020-07-07
  • Javadoc 具體使用詳解

    Javadoc 具體使用詳解

    這篇文章主要介紹了Javadoc 具體使用詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-08-08
  • sprintboot使用spring-security包,緩存內(nèi)存與redis共存方式

    sprintboot使用spring-security包,緩存內(nèi)存與redis共存方式

    這篇文章主要介紹了sprintboot使用spring-security包,緩存內(nèi)存與redis共存方式,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-10-10
  • Java獲取http和https協(xié)議返回的json數(shù)據(jù)

    Java獲取http和https協(xié)議返回的json數(shù)據(jù)

    本篇文章主要介紹了Java獲取http和https協(xié)議返回的json數(shù)據(jù) ,本篇文章提供兩個(gè)方法,幫助各位如何獲取http和https返回的數(shù)據(jù)。有興趣的可以了解一下。
    2017-01-01

最新評論