Java 8 中的 Stream 是对集合(Collection)对象功能的增强,结合Lambda 表达式,极大的提高编程效率和程序可读性
Stream常用的生成方式有:Collection.stream()和Collection.parallelStream(),也可以使用数组Arrays.stream(T array) 或者直接使用Stream.of()
使用Collection接口提供的stream()方法
jdk1.8之后,Collection接口提供了默认方法stream()和parallelStream(),这两个方法返回数据源的流Stream,一个是简单流,一个是并行流。
流的使用分为三个部分,一:数据源,二:数据处理,三:结果输出
例:
List<String> strList = Arrays.asList("d","b","c","a");
strList.stream().sort().forEach(s->System.out.print(s+" "));
结果:a b c d, 源:strList.stream(),加工:sort() ,输出:forEach()
Stream接口
最常使用的流处理方法:
filter,map,distinct,sorted,limit,forEach等,它们返回的返回还是流结果,所以可以组合使用
简单例子说明
List<String> strList = Arrays.asList("1","2","3","4","2","1");
strList.stream().filter(s -> s!="1").forEach(s->System.out.print(s+" "));
>> 2 3 4 2
strList.stream().map(s -> s+"a").forEach(s->System.out.print(s+" "));
>> 1a 2a 3a 4a 2a 1a
strList.stream().distinct().forEach(s->System.out.print(s+" "));
>> 1 2 3 4
strList.stream().filter(s -> s!="a").forEach(s->System.out.print(s+" "));
>> 1 1 2 2 3 4
strList.stream().limit(3).forEach(s->System.out.print(s+" "));
>> 1 2 3
比较复杂的例子
List<Integer> intList = Arrays.asList(7,9,3,4,5,-1,1,-2,-7);
List<Integer> ret = intList.parallelStream().
filter(i -> i > 0).
sorted().
map(i -> i*i).
collect(toList());
ret = [1, 9, 16, 25, 49, 81]