初識(shí)Java8中的Stream
lambda表達(dá)式是stream的基礎(chǔ),初學(xué)者建議先學(xué)習(xí)lambda表達(dá)式,http://www.dhdzp.com/article/121129.htm
1.初識(shí)stream
先來(lái)一個(gè)總綱:

東西就是這么多啦,stream是java8中加入的一個(gè)非常實(shí)用的功能,最初看時(shí)以為是io中的流(其實(shí)一點(diǎn)關(guān)系都沒(méi)有),讓我們先來(lái)看一個(gè)小例子感受一下:
@Before
public void init() {
random = new Random();
stuList = new ArrayList<Student>() {
{
for (int i = 0; i < 100; i++) {
add(new Student("student" + i, random.nextInt(50) + 50));
}
}
};
}
public class Student {
private String name;
private Integer score;
//-----getters and setters-----
}
//1列出班上超過(guò)85分的學(xué)生姓名,并按照分?jǐn)?shù)降序輸出用戶名字
@Test
public void test1() {
List<String> studentList = stuList.stream()
.filter(x->x.getScore()>85)
.sorted(Comparator.comparing(Student::getScore).reversed())
.map(Student::getName)
.collect(Collectors.toList());
System.out.println(studentList);
}
列出班上分?jǐn)?shù)超過(guò)85分的學(xué)生姓名,并按照分?jǐn)?shù)降序輸出用戶名字,在java8之前我們需要三個(gè)步驟:
1)新建一個(gè)List<Student> newList,在for循環(huán)中遍歷stuList,將分?jǐn)?shù)超過(guò)85分的學(xué)生裝入新的集合中
2)對(duì)于新的集合newList進(jìn)行排序操作
3)遍歷打印newList
這三個(gè)步驟在java8中只需要兩條語(yǔ)句,如果緊緊需要打印,不需要保存新生產(chǎn)list的話實(shí)際上只需要一條,是不是非常方便。
2.stream的特性
我們首先列出stream的如下三點(diǎn)特性,在之后我們會(huì)對(duì)照著詳細(xì)說(shuō)明
1.stream不存儲(chǔ)數(shù)據(jù)
2.stream不改變?cè)磾?shù)據(jù)
3.stream的延遲執(zhí)行特性
通常我們?cè)跀?shù)組或集合的基礎(chǔ)上創(chuàng)建stream,stream不會(huì)專門存儲(chǔ)數(shù)據(jù),對(duì)stream的操作也不會(huì)影響到創(chuàng)建它的數(shù)組和集合,對(duì)于stream的聚合、消費(fèi)或收集操作只能進(jìn)行一次,再次操作會(huì)報(bào)錯(cuò),如下代碼:
@Test
public void test1(){
Stream<String> stream = Stream.generate(()->"user").limit(20);
stream.forEach(System.out::println);
stream.forEach(System.out::println);
}

程序在正常完成一次打印工作后報(bào)錯(cuò)。
stream的操作是延遲執(zhí)行的,在列出班上超過(guò)85分的學(xué)生姓名例子中,在collect方法執(zhí)行之前,filter、sorted、map方法還未執(zhí)行,只有當(dāng)collect方法執(zhí)行時(shí)才會(huì)觸發(fā)之前轉(zhuǎn)換操作
看如下代碼:
public boolean filter(Student s) {
System.out.println("begin compare");
return s.getScore() > 85;
}
@Test
public void test() {
Stream<Student> stream = Stream.of(stuArr).filter(this::filter);
System.out.println("split-------------------------------------");
List<Student> studentList = stream.collect(toList());
}
我們將filter中的邏輯抽象成方法,在方法中加入打印邏輯,如果stream的轉(zhuǎn)換操作是延遲執(zhí)行的,那么split會(huì)先打印,否則后打印,代碼運(yùn)行結(jié)果為

可見(jiàn)stream的操作是延遲執(zhí)行的。
TIP:
當(dāng)我們操作一個(gè)流的時(shí)候,并不會(huì)修改流底層的集合(即使集合是線程安全的),如果想要修改原有的集合,就無(wú)法定義流操作的輸出。
由于stream的延遲執(zhí)行特性,在聚合操作執(zhí)行前修改數(shù)據(jù)源是允許的。
List<String> wordList;
@Before
public void init() {
wordList = new ArrayList<String>() {
{
add("a");
add("b");
add("c");
add("d");
add("e");
add("f");
add("g");
}
};
}
/**
* 延遲執(zhí)行特性,在聚合操作之前都可以添加相應(yīng)元素
*/
@Test
public void test() {
Stream<String> words = wordList.stream();
wordList.add("END");
long n = words.distinct().count();
System.out.println(n);
}
最后打印的結(jié)果是8
如下代碼是錯(cuò)誤的
/**
* 延遲執(zhí)行特性,會(huì)產(chǎn)生干擾
* nullPointException
*/
@Test
public void test2(){
Stream<String> words1 = wordList.stream();
words1.forEach(s -> {
System.out.println("s->"+s);
if (s.length() < 4) {
System.out.println("select->"+s);
wordList.remove(s);
System.out.println(wordList);
}
});
}
結(jié)果報(bào)空指針異常

3.創(chuàng)建stream
1)通過(guò)數(shù)組創(chuàng)建
/**
* 通過(guò)數(shù)組創(chuàng)建流
*/
@Test
public void testArrayStream(){
//1.通過(guò)Arrays.stream
//1.1基本類型
int[] arr = new int[]{1,2,34,5};
IntStream intStream = Arrays.stream(arr);
//1.2引用類型
Student[] studentArr = new Student[]{new Student("s1",29),new Student("s2",27)};
Stream<Student> studentStream = Arrays.stream(studentArr);
//2.通過(guò)Stream.of
Stream<Integer> stream1 = Stream.of(1,2,34,5,65);
//注意生成的是int[]的流
Stream<int[]> stream2 = Stream.of(arr,arr);
stream2.forEach(System.out::println);
}
2)通過(guò)集合創(chuàng)建流
/**
* 通過(guò)集合創(chuàng)建流
*/
@Test
public void testCollectionStream(){
List<String> strs = Arrays.asList("11212","dfd","2323","dfhgf");
//創(chuàng)建普通流
Stream<String> stream = strs.stream();
//創(chuàng)建并行流
Stream<String> stream1 = strs.parallelStream();
}
3)創(chuàng)建空的流
@Test
public void testEmptyStream(){
//創(chuàng)建一個(gè)空的stream
Stream<Integer> stream = Stream.empty();
}
4)創(chuàng)建無(wú)限流
@Test
public void testUnlimitStream(){
//創(chuàng)建無(wú)限流,通過(guò)limit提取指定大小
Stream.generate(()->"number"+new Random().nextInt()).limit(100).forEach(System.out::println);
Stream.generate(()->new Student("name",10)).limit(20).forEach(System.out::println);
}
5)創(chuàng)建規(guī)律的無(wú)限流
/**
* 產(chǎn)生規(guī)律的數(shù)據(jù)
*/
@Test
public void testUnlimitStream1(){
Stream.iterate(0,x->x+1).limit(10).forEach(System.out::println);
Stream.iterate(0,x->x).limit(10).forEach(System.out::println);
//Stream.iterate(0,x->x).limit(10).forEach(System.out::println);與如下代碼意思是一樣的
Stream.iterate(0, UnaryOperator.identity()).limit(10).forEach(System.out::println);
}
4.對(duì)stream的操作
1)最常使用
map:轉(zhuǎn)換流,將一種類型的流轉(zhuǎn)換為另外一種流
/**
* map把一種類型的流轉(zhuǎn)換為另外一種類型的流
* 將String數(shù)組中字母轉(zhuǎn)換為大寫
*/
@Test
public void testMap() {
String[] arr = new String[]{"yes", "YES", "no", "NO"};
Arrays.stream(arr).map(x -> x.toLowerCase()).forEach(System.out::println);
}
filter:過(guò)濾流,過(guò)濾流中的元素
@Test
public void testFilter(){
Integer[] arr = new Integer[]{1,2,3,4,5,6,7,8,9,10};
Arrays.stream(arr).filter(x->x>3&&x<8).forEach(System.out::println);
}
flapMap:拆解流,將流中每一個(gè)元素拆解成一個(gè)流
/**
* flapMap:拆解流
*/
@Test
public void testFlapMap1() {
String[] arr1 = {"a", "b", "c", "d"};
String[] arr2 = {"e", "f", "c", "d"};
String[] arr3 = {"h", "j", "c", "d"};
// Stream.of(arr1, arr2, arr3).flatMap(x -> Arrays.stream(x)).forEach(System.out::println);
Stream.of(arr1, arr2, arr3).flatMap(Arrays::stream).forEach(System.out::println);
}
sorted:對(duì)流進(jìn)行排序
String[] arr1 = {"abc","a","bc","abcd"};
/**
* Comparator.comparing是一個(gè)鍵提取的功能
* 以下兩個(gè)語(yǔ)句表示相同意義
*/
@Test
public void testSorted1_(){
/**
* 按照字符長(zhǎng)度排序
*/
Arrays.stream(arr1).sorted((x,y)->{
if (x.length()>y.length())
return 1;
else if (x.length()<y.length())
return -1;
else
return 0;
}).forEach(System.out::println);
Arrays.stream(arr1).sorted(Comparator.comparing(String::length)).forEach(System.out::println);
}
/**
* 倒序
* reversed(),java8泛型推導(dǎo)的問(wèn)題,所以如果comparing里面是非方法引用的lambda表達(dá)式就沒(méi)辦法直接使用reversed()
* Comparator.reverseOrder():也是用于翻轉(zhuǎn)順序,用于比較對(duì)象(Stream里面的類型必須是可比較的)
* Comparator. naturalOrder():返回一個(gè)自然排序比較器,用于比較對(duì)象(Stream里面的類型必須是可比較的)
*/
@Test
public void testSorted2_(){
Arrays.stream(arr1).sorted(Comparator.comparing(String::length).reversed()).forEach(System.out::println);
Arrays.stream(arr1).sorted(Comparator.reverseOrder()).forEach(System.out::println);
Arrays.stream(arr1).sorted(Comparator.naturalOrder()).forEach(System.out::println);
}
/**
* thenComparing
* 先按照首字母排序
* 之后按照String的長(zhǎng)度排序
*/
@Test
public void testSorted3_(){
Arrays.stream(arr1).sorted(Comparator.comparing(this::com1).thenComparing(String::length)).forEach(System.out::println);
}
public char com1(String x){
return x.charAt(0);
}
2)提取流和組合流
@Before
public void init(){
arr1 = new String[]{"a","b","c","d"};
arr2 = new String[]{"d","e","f","g"};
arr3 = new String[]{"i","j","k","l"};
}
/**
* limit,限制從流中獲得前n個(gè)數(shù)據(jù)
*/
@Test
public void testLimit(){
Stream.iterate(1,x->x+2).limit(10).forEach(System.out::println);
}
/**
* skip,跳過(guò)前n個(gè)數(shù)據(jù)
*/
@Test
public void testSkip(){
// Stream.of(arr1).skip(2).limit(2).forEach(System.out::println);
Stream.iterate(1,x->x+2).skip(1).limit(5).forEach(System.out::println);
}
/**
* 可以把兩個(gè)stream合并成一個(gè)stream(合并的stream類型必須相同)
* 只能兩兩合并
*/
@Test
public void testConcat(){
Stream<String> stream1 = Stream.of(arr1);
Stream<String> stream2 = Stream.of(arr2);
Stream.concat(stream1,stream2).distinct().forEach(System.out::println);
}
3)聚合操作
@Before
public void init(){
arr = new String[]{"b","ab","abc","abcd","abcde"};
}
/**
* max、min
* 最大最小值
*/
@Test
public void testMaxAndMin(){
Stream.of(arr).max(Comparator.comparing(String::length)).ifPresent(System.out::println);
Stream.of(arr).min(Comparator.comparing(String::length)).ifPresent(System.out::println);
}
/**
* count
* 計(jì)算數(shù)量
*/
@Test
public void testCount(){
long count = Stream.of(arr).count();
System.out.println(count);
}
/**
* findFirst
* 查找第一個(gè)
*/
@Test
public void testFindFirst(){
String str = Stream.of(arr).parallel().filter(x->x.length()>3).findFirst().orElse("noghing");
System.out.println(str);
}
/**
* findAny
* 找到所有匹配的元素
* 對(duì)并行流十分有效
* 只要在任何片段發(fā)現(xiàn)了第一個(gè)匹配元素就會(huì)結(jié)束整個(gè)運(yùn)算
*/
@Test
public void testFindAny(){
Optional<String> optional = Stream.of(arr).parallel().filter(x->x.length()>3).findAny();
optional.ifPresent(System.out::println);
}
/**
* anyMatch
* 是否含有匹配元素
*/
@Test
public void testAnyMatch(){
Boolean aBoolean = Stream.of(arr).anyMatch(x->x.startsWith("a"));
System.out.println(aBoolean);
}
@Test
public void testStream1() {
Optional<Integer> optional = Stream.of(1,2,3).filter(x->x>1).reduce((x,y)->x+y);
System.out.println(optional.get());
}
4)Optional類型
通常聚合操作會(huì)返回一個(gè)Optional類型,Optional表示一個(gè)安全的指定結(jié)果類型,所謂的安全指的是避免直接調(diào)用返回類型的null值而造成空指針異常,調(diào)用optional.ifPresent()可以判斷返回值是否為空,或者直接調(diào)用ifPresent(Consumer<? super T> consumer)在結(jié)果部位空時(shí)進(jìn)行消費(fèi)操作;調(diào)用optional.get()獲取返回值。通常的使用方式如下:
@Test
public void testOptional() {
List<String> list = new ArrayList<String>() {
{
add("user1");
add("user2");
}
};
Optional<String> opt = Optional.of("andy with u");
opt.ifPresent(list::add);
list.forEach(System.out::println);
}
使用Optional可以在沒(méi)有值時(shí)指定一個(gè)返回值,例如
@Test
public void testOptional2() {
Integer[] arr = new Integer[]{4,5,6,7,8,9};
Integer result = Stream.of(arr).filter(x->x>9).max(Comparator.naturalOrder()).orElse(-1);
System.out.println(result);
Integer result1 = Stream.of(arr).filter(x->x>9).max(Comparator.naturalOrder()).orElseGet(()->-1);
System.out.println(result1);
Integer result2 = Stream.of(arr).filter(x->x>9).max(Comparator.naturalOrder()).orElseThrow(RuntimeException::new);
System.out.println(result2);
}
Optional的創(chuàng)建
采用Optional.empty()創(chuàng)建一個(gè)空的Optional,使用Optional.of()創(chuàng)建指定值的Optional。同樣也可以調(diào)用Optional對(duì)象的map方法進(jìn)行Optional的轉(zhuǎn)換,調(diào)用flatMap方法進(jìn)行Optional的迭代
@Test
public void testStream1() {
Optional<Student> studentOptional = Optional.of(new Student("user1",21));
Optional<String> optionalStr = studentOptional.map(Student::getName);
System.out.println(optionalStr.get());
}
public static Optional<Double> inverse(Double x) {
return x == 0 ? Optional.empty() : Optional.of(1 / x);
}
public static Optional<Double> squareRoot(Double x) {
return x < 0 ? Optional.empty() : Optional.of(Math.sqrt(x));
}
/**
* Optional的迭代
*/
@Test
public void testStream2() {
double x = 4d;
Optional<Double> result1 = inverse(x).flatMap(StreamTest7::squareRoot);
result1.ifPresent(System.out::println);
Optional<Double> result2 = Optional.of(4.0).flatMap(StreamTest7::inverse).flatMap(StreamTest7::squareRoot);
result2.ifPresent(System.out::println);
}
5)收集結(jié)果
Student[] students;
@Before
public void init(){
students = new Student[100];
for (int i=0;i<30;i++){
Student student = new Student("user",i);
students[i] = student;
}
for (int i=30;i<60;i++){
Student student = new Student("user"+i,i);
students[i] = student;
}
for (int i=60;i<100;i++){
Student student = new Student("user"+i,i);
students[i] = student;
}
}
@Test
public void testCollect1(){
/**
* 生成List
*/
List<Student> list = Arrays.stream(students).collect(toList());
list.forEach((x)-> System.out.println(x));
/**
* 生成Set
*/
Set<Student> set = Arrays.stream(students).collect(toSet());
set.forEach((x)-> System.out.println(x));
/**
* 如果包含相同的key,則需要提供第三個(gè)參數(shù),否則報(bào)錯(cuò)
*/
Map<String,Integer> map = Arrays.stream(students).collect(toMap(Student::getName,Student::getScore,(s,a)->s+a));
map.forEach((x,y)-> System.out.println(x+"->"+y));
}
/**
* 生成數(shù)組
*/
@Test
public void testCollect2(){
Student[] s = Arrays.stream(students).toArray(Student[]::new);
for (int i=0;i<s.length;i++)
System.out.println(s[i]);
}
/**
* 指定生成的類型
*/
@Test
public void testCollect3(){
HashSet<Student> s = Arrays.stream(students).collect(toCollection(HashSet::new));
s.forEach(System.out::println);
}
/**
* 統(tǒng)計(jì)
*/
@Test
public void testCollect4(){
IntSummaryStatistics summaryStatistics = Arrays.stream(students).collect(Collectors.summarizingInt(Student::getScore));
System.out.println("getAverage->"+summaryStatistics.getAverage());
System.out.println("getMax->"+summaryStatistics.getMax());
System.out.println("getMin->"+summaryStatistics.getMin());
System.out.println("getCount->"+summaryStatistics.getCount());
System.out.println("getSum->"+summaryStatistics.getSum());
}
6)分組和分片
分組和分片的意義是,將collect的結(jié)果集展示位Map<key,val>的形式,通常的用法如下:
Student[] students;
@Before
public void init(){
students = new Student[100];
for (int i=0;i<30;i++){
Student student = new Student("user1",i);
students[i] = student;
}
for (int i=30;i<60;i++){
Student student = new Student("user2",i);
students[i] = student;
}
for (int i=60;i<100;i++){
Student student = new Student("user3",i);
students[i] = student;
}
}
@Test
public void testGroupBy1(){
Map<String,List<Student>> map = Arrays.stream(students).collect(groupingBy(Student::getName));
map.forEach((x,y)-> System.out.println(x+"->"+y));
}
/**
* 如果只有兩類,使用partitioningBy會(huì)比groupingBy更有效率
*/
@Test
public void testPartitioningBy(){
Map<Boolean,List<Student>> map = Arrays.stream(students).collect(partitioningBy(x->x.getScore()>50));
map.forEach((x,y)-> System.out.println(x+"->"+y));
}
/**
* downstream指定類型
*/
@Test
public void testGroupBy2(){
Map<String,Set<Student>> map = Arrays.stream(students).collect(groupingBy(Student::getName,toSet()));
map.forEach((x,y)-> System.out.println(x+"->"+y));
}
/**
* downstream 聚合操作
*/
@Test
public void testGroupBy3(){
/**
* counting
*/
Map<String,Long> map1 = Arrays.stream(students).collect(groupingBy(Student::getName,counting()));
map1.forEach((x,y)-> System.out.println(x+"->"+y));
/**
* summingInt
*/
Map<String,Integer> map2 = Arrays.stream(students).collect(groupingBy(Student::getName,summingInt(Student::getScore)));
map2.forEach((x,y)-> System.out.println(x+"->"+y));
/**
* maxBy
*/
Map<String,Optional<Student>> map3 = Arrays.stream(students).collect(groupingBy(Student::getName,maxBy(Comparator.comparing(Student::getScore))));
map3.forEach((x,y)-> System.out.println(x+"->"+y));
/**
* mapping
*/
Map<String,Set<Integer>> map4 = Arrays.stream(students).collect(groupingBy(Student::getName,mapping(Student::getScore,toSet())));
map4.forEach((x,y)-> System.out.println(x+"->"+y));
}
5.原始類型流
在數(shù)據(jù)量比較大的情況下,將基本數(shù)據(jù)類型(int,double...)包裝成相應(yīng)對(duì)象流的做法是低效的,因此,我們也可以直接將數(shù)據(jù)初始化為原始類型流,在原始類型流上的操作與對(duì)象流類似,我們只需要記住兩點(diǎn)
1.原始類型流的初始化
2.原始類型流與流對(duì)象的轉(zhuǎn)換
DoubleStream doubleStream;
IntStream intStream;
/**
* 原始類型流的初始化
*/
@Before
public void testStream1(){
doubleStream = DoubleStream.of(0.1,0.2,0.3,0.8);
intStream = IntStream.of(1,3,5,7,9);
IntStream stream1 = IntStream.rangeClosed(0,100);
IntStream stream2 = IntStream.range(0,100);
}
/**
* 流與原始類型流的轉(zhuǎn)換
*/
@Test
public void testStream2(){
Stream<Double> stream = doubleStream.boxed();
doubleStream = stream.mapToDouble(Double::new);
}
6.并行流
可以將普通順序執(zhí)行的流轉(zhuǎn)變?yōu)椴⑿辛?,只需要調(diào)用順序流的parallel() 方法即可,如Stream.iterate(1, x -> x + 1).limit(10).parallel()。
1) 并行流的執(zhí)行順序
我們調(diào)用peek方法來(lái)瞧瞧并行流和串行流的執(zhí)行順序,peek方法顧名思義,就是偷窺流內(nèi)的數(shù)據(jù),peek方法聲明為Stream<T> peek(Consumer<? super T> action);加入打印程序可以觀察到通過(guò)流內(nèi)數(shù)據(jù),見(jiàn)如下代碼:
public void peek1(int x) {
System.out.println(Thread.currentThread().getName() + ":->peek1->" + x);
}
public void peek2(int x) {
System.out.println(Thread.currentThread().getName() + ":->peek2->" + x);
}
public void peek3(int x) {
System.out.println(Thread.currentThread().getName() + ":->final result->" + x);
}
/**
* peek,監(jiān)控方法
* 串行流和并行流的執(zhí)行順序
*/
@org.junit.Test
public void testPeek() {
Stream<Integer> stream = Stream.iterate(1, x -> x + 1).limit(10);
stream.peek(this::peek1).filter(x -> x > 5)
.peek(this::peek2).filter(x -> x < 8)
.peek(this::peek3)
.forEach(System.out::println);
}
@Test
public void testPeekPal() {
Stream<Integer> stream = Stream.iterate(1, x -> x + 1).limit(10).parallel();
stream.peek(this::peek1).filter(x -> x > 5)
.peek(this::peek2).filter(x -> x < 8)
.peek(this::peek3)
.forEach(System.out::println);
}
串行流打印結(jié)果如下:

并行流打印結(jié)果如下:

咋看不一定能看懂,我們用如下的圖來(lái)解釋

我們將stream.filter(x -> x > 5).filter(x -> x < 8).forEach(System.out::println)的過(guò)程想象成上圖的管道,我們?cè)诠艿郎霞尤氲膒eek相當(dāng)于一個(gè)閥門,透過(guò)這個(gè)閥門查看流經(jīng)的數(shù)據(jù),
1)當(dāng)我們使用順序流時(shí),數(shù)據(jù)按照源數(shù)據(jù)的順序依次通過(guò)管道,當(dāng)一個(gè)數(shù)據(jù)被filter過(guò)濾,或者經(jīng)過(guò)整個(gè)管道而輸出后,第二個(gè)數(shù)據(jù)才會(huì)開(kāi)始重復(fù)這一過(guò)程
2)當(dāng)我們使用并行流時(shí),系統(tǒng)除了主線程外啟動(dòng)了七個(gè)線程(我的電腦是4核八線程)來(lái)執(zhí)行處理任務(wù),因此執(zhí)行是無(wú)序的,但同一個(gè)線程內(nèi)處理的數(shù)據(jù)是按順序進(jìn)行的。
2) sorted()、distinct()等對(duì)并行流的影響
sorted()、distinct()是元素相關(guān)方法,和整體的數(shù)據(jù)是有關(guān)系的,map,filter等方法和已經(jīng)通過(guò)的元素是不相關(guān)的,不需要知道流里面有哪些元素 ,并行執(zhí)行和sorted會(huì)不會(huì)產(chǎn)生沖突呢?
結(jié)論:1.并行流和排序是不沖突的,2.一個(gè)流是否是有序的,對(duì)于一些api可能會(huì)提高執(zhí)行效率,對(duì)于另一些api可能會(huì)降低執(zhí)行效率
3.如果想要輸出的結(jié)果是有序的,對(duì)于并行的流需要使用forEachOrdered(forEach的輸出效率更高)
我們做如下實(shí)驗(yàn):
/**
* 生成一億條0-100之間的記錄
*/
@Before
public void init() {
Random random = new Random();
list = Stream.generate(() -> random.nextInt(100)).limit(100000000).collect(toList());
}
/**
* tip
*/
@org.junit.Test
public void test1() {
long begin1 = System.currentTimeMillis();
list.stream().filter(x->(x > 10)).filter(x->x<80).count();
long end1 = System.currentTimeMillis();
System.out.println(end1-begin1);
list.stream().parallel().filter(x->(x > 10)).filter(x->x<80).count();
long end2 = System.currentTimeMillis();
System.out.println(end2-end1);
long begin1_ = System.currentTimeMillis();
list.stream().filter(x->(x > 10)).filter(x->x<80).distinct().sorted().count();
long end1_ = System.currentTimeMillis();
System.out.println(end1-begin1);
list.stream().parallel().filter(x->(x > 10)).filter(x->x<80).distinct().sorted().count();
long end2_ = System.currentTimeMillis();
System.out.println(end2_-end1_);
}

可見(jiàn),對(duì)于串行流.distinct().sorted()方法對(duì)于運(yùn)行時(shí)間沒(méi)有影響,但是對(duì)于串行流,會(huì)使得運(yùn)行時(shí)間大大增加,因此對(duì)于包含sorted、distinct()等與全局?jǐn)?shù)據(jù)相關(guān)的操作,不推薦使用并行流。
7.stream vs spark rdd
最初看到stream的一個(gè)直觀感受是和spark像,真的像
val count = sc.parallelize(1 to NUM_SAMPLES).filter { _ =>
val x = math.random
val y = math.random
x*x + y*y < 1}.count()println(s"Pi is roughly ${4.0 * count / NUM_SAMPLES}")
以上代碼摘自spark官網(wǎng),使用的是scala語(yǔ)言,一個(gè)最基礎(chǔ)的word count代碼,這里我們簡(jiǎn)單介紹一下spark,spark是當(dāng)今最流行的基于內(nèi)存的大數(shù)據(jù)處理框架,spark中的一個(gè)核心概念是RDD(彈性分布式數(shù)據(jù)集),將分布于不同處理器上的數(shù)據(jù)抽象成rdd,rdd上支持兩種類型的操作1) Transformation(變換)2) Action(行動(dòng)),對(duì)于rdd的Transformation算子并不會(huì)立即執(zhí)行,只有當(dāng)使用了Action算子后,才會(huì)觸發(fā)。

總結(jié)
以上所示是小編給大家介紹的Java8中的Stream相關(guān)知識(shí),希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)歡迎給我留言,小編會(huì)及時(shí)回復(fù)大家的!
相關(guān)文章
教你利用springboot集成swagger并生成接口文檔
有很多小伙伴不會(huì)利用springboot集成swagger并生成接口文檔,今天特地整理了這篇文章,文中有非常詳細(xì)的代碼圖文介紹及代碼示例,對(duì)不會(huì)這個(gè)方法的小伙伴們很有幫助,需要的朋友可以參考下2021-05-05
SpringBoot個(gè)性化啟動(dòng)Banner設(shè)置方法解析
這篇文章主要介紹了SpringBoot個(gè)性化啟動(dòng)Banner設(shè)置方法解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-03-03
springboot整合持久層的方法實(shí)現(xiàn)
本文主要介紹了springboot整合持久層的方法實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-09-09
Java實(shí)現(xiàn)計(jì)網(wǎng)循環(huán)冗余檢驗(yàn)算法的方法示例
這篇文章主要給大家介紹了關(guān)于Java實(shí)現(xiàn)計(jì)網(wǎng)循環(huán)冗余檢驗(yàn)算法的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04
SpringBoot+Redis布隆過(guò)濾器防惡意流量擊穿緩存
本文主要介紹了SpringBoot+Redis布隆過(guò)濾器防惡意流量擊穿緩存,文中根據(jù)實(shí)例編碼詳細(xì)介紹的十分詳盡,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-03-03
springboot整合netty-mqtt-client實(shí)現(xiàn)Mqtt消息的訂閱和發(fā)布示例
本文主要介紹了springboot整合netty-mqtt-client實(shí)現(xiàn)Mqtt消息的訂閱和發(fā)布示例,文中根據(jù)實(shí)例編碼詳細(xì)介紹的十分詳盡,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-03-03
關(guān)于struts返回對(duì)象json格式數(shù)據(jù)的方法
以下為大家介紹,關(guān)于struts返回對(duì)象json格式數(shù)據(jù)的方法,希望對(duì)有需要的朋友有所幫助。2013-04-04
Java將byte[]轉(zhuǎn)圖片存儲(chǔ)到本地的案例
這篇文章主要介紹了Java將byte[]轉(zhuǎn)圖片存儲(chǔ)到本地的案例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-10-10

