Java8新特性——流介面Streams__Java

來源:互聯網
上載者:User

今天是高考的日子,是大四師兄師姐答辯畢業的日子。一代又來,一代又去。好久沒寫部落格,藉此特殊日子整理一下前不久學java8新特性時寫的代碼,留下痕迹。(本部落格的代碼根據 java8新特性教程 學習整理,加上個人的理解而成,關於某個新特性的介紹代碼裡的注釋已經闡述清楚,故不再寫文字介紹,直接看代碼吧。)


    本篇介紹java8的新特性之一:流介面Streams。  

import java.util.ArrayList;import java.util.List;import java.util.Optional;import org.junit.Test;/** * 流介面(Streams)java.util.Stream代表著一串你可以在其上進行多種操作的元素。流操作既可以是連續的也可以是中斷的。中斷操作返回操作結果。而連續操作返迴流本身,這樣你就可以在該行上鏈式方法調用。流是建立在資料來源上的,例如:java.util.Collection、list集合和set集合(Map不支援)。流操作既可以順序執行也可以並存執行。我們首先瞭解下順序的流是如何工作的。我們首先建立一個字串鏈表。 */public class StreamDemo {static List<String> stringCollection = new ArrayList<>();static{stringCollection.add("ddd2");stringCollection.add("aaa2");stringCollection.add("bbb1");stringCollection.add("aaa1");stringCollection.add("bbb3");stringCollection.add("ccc");stringCollection.add("bbb2");stringCollection.add("ddd1");}//Java8的Collections類已經被擴充了,你可以簡單的調用Collection.stream()或者Collection.parallelSteam()來建立流。//下面部分將介紹大部分流操作。/** * Filter接受一個predicate來過濾流中的所有元素。這個操作是連續的,它可以讓我們在結果上繼續調用另外一個流操作forEach。 * ForEach接受一個consumer,它被用來對過濾流中的每個元素執行操作。ForEach是一個中斷操作.  * forEach返回void,因此我們不能在ForEach後調用其他流操作。 */@Testpublic void Filter(){ stringCollection.stream().filter( (s) ->s.startsWith("a") ).forEach(System.out::println);// "aaa2" , "aaa1"}/** * Sorted is an intermediate operation which returns a sorted view of the stream.  * The elements are sorted in natural order unless you pass a custom Comparator. */@Testpublic void Sorted(){stringCollection.stream().sorted().filter( (s) -> s.startsWith("a") ).forEach(System.out::println);// "aaa1" , "aaa2"//Keep in mind that sorted does only create a sorted view of the stream //without manipulating the ordering of the backed collection.//The ordering of stringCollection is untouched:System.out.println(stringCollection); //[ddd2, aaa2, bbb1, aaa1, bbb3, ccc, bbb2, ddd1]}/** * Map連續性操作map通過指定的Function將流中的每個元素轉變為另外的對象。下面的樣本將每個字串轉換為大寫的字串。此外,你也可以使用map將每個元素的類型改變為其它類型。轉換後流的泛型型別依賴於你傳入的Function的泛型型別。 */@Testpublic void Map(){stringCollection.stream().map(String::toUpperCase).sorted( (a, b) -> b.compareTo(a)).forEach(System.out::print);// // "DDD2", "DDD1", "CCC", "BBB3", "BBB2", "AAA2", "AAA1"  }/** * 各種匹配操作可以用來檢測某種predicate是否和流中元素相匹配。所有的這些操作是中斷的並返回一個boolean結果。 */@Testpublic void Match(){boolean anyStartWithA = stringCollection.stream().anyMatch((s) -> s.startsWith("a"));System.err.println(anyStartWithA); // trueboolean allStartWithA = stringCollection.stream().allMatch((s)->s.startsWith("a"));System.err.println(allStartWithA); // falseboolean noneStartWithA = stringCollection.stream().noneMatch((s) -> s.startsWith("z"));System.err.println(noneStartWithA); // true}/** * CountCount是中斷型操作,它返迴流中的元素數量。 */@Testpublic void Count(){long startWithB = stringCollection.stream().filter((s)->s.startsWith("b")).count();System.err.println(startWithB); // 3}/** * Reduce * 這個中斷性操作使用指定的function對流中元素實施消減策略。此操作的傳回值是一個包括所有被消減元素的Optional。 */@Testpublic void Reduce(){Optional<String> optional = stringCollection.stream().sorted().reduce((s1, s2)->s1+"#"+s2 );optional.ifPresent(System.out::print);// aaa1#aaa2#bbb1#bbb2#bbb3#ccc#ddd1#ddd2}}

詳情請見這篇部落格:  java8新特性教程 


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.