Java 8新特性五:Stream API
重视:Java提高营,最新文章第一时间送达,10T 免费学习材料随时领取!!!
Stream概念
Stream(流)是一个来自数据源的元素队列并支撑聚合操作
Stream API可以极大提高Java程序员的生产力,让程序员写出[ # $ Z , ] _高效率、干净、简练的代码。
这种风格即将处理的元素调集看作一种流,流在管道中传输,并且可以在管道的节点上进行处理,k Z ] ( Q + 比如筛选, 排序,聚合等。
Java Stream的特性
- Stream不是一种数据结构,而是一个来自数据源的元素队列并支撑聚合操作
- Stream不会改动来源的数7 m P @ Q r据结构
- 每个中心操作都是延迟履行的,并$ * 9 6 q r & =回来一个流,元素流在管道中经过中8 M O %心操作(intermediate operation)的处理u Q | Y w r #,最后由终究操作(terminal operation)得到前面处理# I R F X l的成果

以上的流程转换成Java代码为:
List<Integer> transaI s c JctionsIds =
widgets.stream()
.filter(b -> b.getColor() == RED)
.sorted((x,y) -> x.get= a z L H 8 3 ~ KWeig_ D Ght() - y.getWeight())
.mm ^ q K YapToInt(Widget::getWB @ i . W 8 n , Geight)
.sum();
生成Strw g a Q : Meam
在java 8中, 调集接口有两个办法来生成流:
- stream() − 为调集创立串行6 a d ` ! R Q G流。
List&lc . 9 ; 7 )t;String> strings =6 f V g h Arrays.asList("abcg G r y _ . L G",j I ~ "", "bc", "efg",i G $ ] / C Z B # "abc= o J P rd","", "jkl");
List<String> filtered = strings.stream().filter(string -> !strin6 $ ^ r Y 3 gg.isEmpty()).collect(Collectors.toList());H ! # $ h ] { M
- parallelStream() − 为调集创立并行流。
List<String> strings = Arrays.asList(o P W"abc", "", "bc", "efg", "abcd","", "jkl");
// 获取空字符串的数量
int count = strings.parallelStream().filter(string -> string.isEmpty()).count();
在Stream上进行操作
中心操作(intermediate operation)
- map: map 办法用于映射每个元素到对应的成果
List number = Arrays.asList(2,3,4,5_ + j ; * | ; 6);
Lin k ` s i L ~ Bst square = number.stream().map(x->x*x).collect(Collectors.toList());L . U D & j G u
- filter: filter 办法用于经过设@ H 5 j +置的条件过滤出元素
List names = Arrays.asList("Reflection) U G g","Collectiw m | Lon","Stream");
List result = names= { ( E u _.stream().filter(s->s.startsWith("S")).collect(Collectors.toList());
- sorted: sorted 办法用6 @ ` ? $ ( y x于对流进行排序
List names = Arrays.asList("Reflection","Collection","Strp ] ^ q x ream");
Li3 - _ ]st result = names.stream().sorted().collect(Collectors.toList());
- limit:limit 办法用于获取指定数量的流
Random random = new Random();
ran8 5 W ? l Ldom.ints().limit(10).forEach(System.1 h q g = n _outj f V::println);
终究操作(terminal operation)
- collect: colI 2 W q C y V 5lect办法用于回来履行中心操作后的成果
List number = Arrays.asList(2,3,4,5,3);
Sy 2 ? , ` X 5 J Cet square = number.stream().map(x->x*x).colle, G o c , ( %ct(Collectors.toSet());e 5 w
- forEach:forEach 办法用来迭代流中的每个数据
Random random = new Random();
random.ints().limit(10).forEa_ } 5 d z 5 F 7 Pch(System.out::println);
- reduce: reduce办法用于将流的元素计算后输出一个值
//red5 o Y . s 8 N uce办法将Bin4 - 0 3 G h 0aryOperator用作参数
//在这里,anD o b A A D ` ws变量初始值为0
List number = Arrays.asList(2,3,4. I { N g o ,5);
int even = number.stream().filter(x->x%2==0).reduce(0,(ans,i)-> ans+i);
Stream示例
//a simple prt R o a V ; r qogram@ b 9 ( d S to demonstrate the use of stream in java
import ja( f ; #va.util.*;$ o . J ; u |
import java.util.sA * f ! p Ytream.*;
claI ; e Gss Dem& + c e eo
{
publJ a 7 eic static void main(String args[]) {
// create a list of integers
List<Integer> number = Arrays.asList(2,3,4,5);
// deD # I monstration of map method
LW a p 9 e 6 i jist<Int3 ; Zeger> square = number.stream().map(x -> x*x).collect(] H 1 S % J } K jColle; F ~ M jc` R c 8 O gtors.toList());
Ss L ^ *ystem.out.println(square);
// create a l^ I 0 ) [ 3ist of SU c Htring
List<String> names = Arrays.asList("Reflection","Collection",, P 6 W"Stream");
// demonstration of filter method
List<String>S g { d Q result = names.stream().filter(s->s.startsWith("S")).
collect(Collectors.toL% w [ [ Uist());
System.out.println(result);
// demonstration of sorted metho$ J $ P Q bd
List<String> show = names.stream().sorted().collect(CoI g ^ F P Y -llectors.toList());
System.oute F L H L ;.println(show);
// create a list of integers
List<Integew 9 D Y {r> numbers = Arrays.asLisJ i 7 d ^ P ?t(2,3,4,5,2);
// collect method returns a set
Set<Integer> squareSet = numbers.stream().map(x->x*x).c0 / a s % ) c Rollect(Collectt r z cors.toSet());
System.out.println(squareSet);
// demonstD V 3 F c k G mration of forEach method
number.stream().map(x->x*x).forEach(y->System.out.println(y));
/: . N d u l/ demonstration of reduce method
int even = number.stream().filter(x->x%2==0).reduce(0,(anso n ? m 7,i)-> ans+i);
System.out.printt = V 1 A 9 3 G Rln(even);
}
}
输出:
[4, 9, 16, 25]
[Stream]
[CollE K x P 2 u Xection, Reflection, Stream]
[16, 4, 9, 25]
4
9
16
25
6