Stream是Java8中处理集合的关键抽象概念,它可以指定你希望对集合进行的操作,可以执行非常复杂的查找、过滤和映射数据等操作。使用Stream API对集合数据进行操作,就类似于使用SQL执行的数据库查询。也可以使用Stream API来并行执行操作。简而言之,Stream API提供了一种高效且易于使用的处理数据的方式。
流(Stream)是数据渠道,用于操作数据源(集合、数组等)所生成的元素序列。
集合讲的是数据,流讲的是计算。
一个数据源(如:集合、数组),获取一个流。
一个中间操作链,对数据源的数据进行处理。
Java8中的Collection接口被扩展,提供了两个获取流的方式:
default Stream stream()
:返回一个顺序流。default Stream parallelStream()
:返回一个并行流。/**
* 创建Stream
*/
@Test
public void test1(){
//1.Collection提供了两个方法stream() 与 parallelStream()
List<String> list = new ArrayList<>();
//获取一个顺序流
Stream<String> stream = list.stream();
//获取一个并行流
Stream<String> stream1 = list.parallelStream();
//2.通过Arrays的stream()获取一个数组流,数组获取流只能这样获取
Integer[] nums = new Integer[10];
Stream<Integer> stream2 = Arrays.stream(nums);
//3.通过Stream类中的静态方法 of() 获取流
Stream<Integer> stream3 = Stream.of(1, 2, 3, 4, 5);
//4.创建无限流,以0为起始值,做一元运算,取10个
Stream<Integer> stream4 = Stream.iterate(0, (x) -> x + 2).limit(10);
stream4.forEach(System.out::println);
//5.生成,随机生成数,取两个。Math::random只能这么写,如果按照普通方法调用Math.random会报错
//因为generate中传的是供给型接口,不需要参数,但有返回值
Stream<Double> stream5 = Stream.generate(Math::random).limit(2);
stream5.forEach(System.out::println);
}
多个中间操作可以连接起来形成一个流水线,除非流水线上触发终止操作,否则中间操作不会执行任何的处理!而在终止操作时一次性全部处理,称为“惰性求值”,也叫延迟加载。
中间操作返回的值,还是一个Stream流对象。
方法 | 描述 |
---|---|
filter(Predicate p) | 接收Lambda,从流中排除元素。接收的lambda是一个断言型接口,接收一个参数,返回boolean值 |
distinct() | 筛选,去重。通过流所生成元素的hashCode()和equals()去除重复元素 |
limit(long maxSize) | 截断流,使其元素不超过给定数量 |
skip(long n) | 跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一个空流。与limit(n)互补 |
将要用到的pojo类,Employee
package com.wangwren.exer;
import org.w3c.dom.NameList;
import java.util.Objects;
/**
* @author: wangwren
* @date: 2019/3/30
* @descripton:
* @version: 1.0
*/
public class Employee {
private Integer id;
private String name;
private Integer age;
private Double salary;
private Status status;
public Employee() {
}
public Employee(String name,Integer age){
this.name = name;
this.age = age;
}
public Employee(Integer id, String name, Integer age, Double salary) {
this.id = id;
this.name = name;
this.age = age;
this.salary = salary;
}
public Employee(Integer id, String name, Integer age, Double salary, Status status) {
this.id = id;
this.name = name;
this.age = age;
this.salary = salary;
this.status = status;
}
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", salary=" + salary +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass())
return false;
Employee employee = (Employee) o;
return Objects.equals(id, employee.id) &&
Objects.equals(name, employee.name) &&
Objects.equals(age, employee.age) &&
Objects.equals(salary, employee.salary);
}
@Override
public int hashCode() {
return Objects.hash(id, name, age, salary);
}
public enum Status{
BUSY,
FREE,
VOCATION;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public String show(){
return "测试方法引用";
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Double getSalary() {
return salary;
}
public void setSalary(Double salary) {
this.salary = salary;
}
}
//2.中间操作
List<Employee> emps = Arrays.asList(
new Employee(102, "李四", 59, 6666.66),
new Employee(101, "张三", 18, 9999.99),
new Employee(103, "王五", 28, 3333.33),
new Employee(104, "赵六", 8, 7777.77),
new Employee(104, "赵六", 8, 7777.77),
new Employee(104, "赵六", 8, 7777.77),
new Employee(105, "田七", 38, 5555.55)
);
/**
* 筛选与切片
* filter:接收Lambda,从流中排除某些元素
* limit:截断流,使其元素不超过给定数量
* skip(n):跳过元素,返回一个扔掉了前n个元素的流。若流中元素不足 n 个,则返回一个空流。与limit互补。
* distinct:筛选,通过流所生成元素的hashCode()和equals()去除重复元素。
*/
@Test
public void test2(){
//过滤操作,返回年龄小于等于35的
//所有的中间操作不会做任何处理
Stream<Employee> stream = emps.stream().filter((e) -> {
System.out.println("测试中间操作");
return e.getAge() <= 35;
});
//终止操作,forEach遍历一下
//只有当做终止操作时,所有的中间操作会一次性的全部执行,称为“惰性求值”
//内部迭代,迭代操作Stream API内部完成
stream.forEach(System.out::println);
}
//这是外部迭代,需要自己写
@Test
public void test3(){
Iterator<Employee> iterator = emps.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
}
/**
* limit操作,带有短路效果
*通过打印结果可以看出,filter过滤会一个一个数据进行判断,这里limit设为3
* 当已经有3个值满足时,就不会再进行中间操作了,即后面的数据不会进行操作,称为短路,
* 与 &&,|| 短路相似
*/
@Test
public void test4(){
emps.stream()
.filter((e) -> {
System.out.println("短路");
return e.getSalary() >= 5000;
})
.limit(3)
.forEach(System.out::println);
}
/**
* skip操作
*/
@Test
public void test5(){
//扔掉满足过滤的条件的前两个数据
emps.stream()
.filter((e) -> e.getSalary() >= 5000)
.skip(2)
.forEach(System.out::println);
}
/**
* distinct去重操作
* 这里Employee是自己定义的类,需要重写hashCode和equals()方法
* 去重才有效果,否则去不了重复
*/
@Test
public void test6(){
emps.stream()
.distinct()
.forEach(System.out::println);
}
方法 | 描述 |
---|---|
map(Function f) | 接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。 |
mapToDouble(ToDoubleFunction f) | 接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的DoubleStream. |
mapToInt(ToIntFunction f) | 接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的IntStream。 |
mapToLong(ToLongFunction f) | 接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的LongStream。 |
flatMap(Function f) | 接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流。 |
/**
* 映射
* map:接收Lambda,将元素转换成其他形式或提取信息。
* 接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素
*
* flatMap:接收一个函数作为参数,将流中的每个值都换成另一个流。然后把所有流连接成一个流
*
*/
@Test
public void test1(){
Stream<String> stream = emps.stream()
.map((e) -> e.getName());
System.out.println("-----------------------");
List<String> strList = Arrays.asList("aaa","bbb","ccc","ddd");
//通过map,其中传入一个转大写的函数
Stream<String> stream1 = strList.stream()
.map(String::toUpperCase);
//遍历输出stream1流,发现数据全变大写了,原本的strList没变
stream1.forEach(System.out::println);
System.out.println("--------------------------");
//使用map去调用自定义的方法
//看这个变量的定义,是一个Stream中还有一个Stream
Stream<Stream<Character>> stream2 = strList.stream()
.map(TestStreamAPI2::filterCharacter);
stream2.forEach((sm) -> {
sm.forEach(System.out::println);
});
System.out.println("----------------------------");
//使用flatMap去调用自定义方法
//注意看这个变量的定义,与stream2的区别,这就是合并成一个流了
Stream<Character> stream3 = strList.stream()
.flatMap(TestStreamAPI2::filterCharacter);
stream3.forEach(System.out::println);
}
/**
* 自定义方法:接收一个字符串
* 取出字符串中的字符,添加至list集合中
* 返回list集合的stream流
*/
public static Stream<Character> filterCharacter(String str){
List<Character> list = new ArrayList<>();
for (Character ch : str.toCharArray()){
list.add(ch);
}
return list.stream();
}
方法 | 描述 |
---|---|
sorted() | 产生一个新流,其中按自然顺序排序。 |
sorted(Comparator comp) | 产生一个新流,其中按比较器顺序排序 |
/**
* sorted():自然排序
* sorted(Comparator com):定制排序
*/
@Test
public void test2(){
//自然排序
emps.stream()
.map(Employee::getName)
.sorted()
.forEach(System.out::println);
System.out.println("-------------------");
//定制排序
emps.stream()
.sorted((x,y) -> {
if (x.getAge().equals(y.getAge())){
return x.getName().compareTo(y.getName());
}else {
return Integer.compare(x.getAge(),y.getAge());
}
})
.forEach(System.out::println);
}
终止操作会从流的流水线生产结果。其结果可以是任何不是流的值。例如:List、Integer,甚至是void。
终止操作与中间操作相比,终止操作返回值已经不再是Stream流对象了,所以叫终止操作,能够获取到对应的值了。
方法 | 描述 |
---|---|
allMatch(Predicate p) | 检查是否匹配所有元素 |
anyMatch(Predicate p) | 检查是否至少匹配一个元素 |
noneMatch(Predicate p) | 检查是否没有匹配所有元素 |
findFirst() | 返回第一个元素 |
findAny() | 返回当前流中的任意元素 |
count() | 返回流中元素总数 |
max(Comparator c) | 返回流中最大值 |
min(Comparator c) | 返回流中最小值 |
forEach(Consumer c) | 内部迭代(使用Collection接口需要用户去做迭代,称为外部迭代。相反,Stream API使用内部迭代,它帮你把迭代做了) |
public class TestStreamAPI3 {
List<Employee> emps = Arrays.asList(
new Employee(102, "李四", 59, 6666.66,Employee.Status.BUSY),
new Employee(101, "张三", 18, 9999.99, Employee.Status.FREE),
new Employee(103, "王五", 28, 3333.33, Employee.Status.VOCATION),
new Employee(104, "赵六", 8, 7777.77, Employee.Status.BUSY),
new Employee(104, "赵六", 8, 7777.77, Employee.Status.FREE),
new Employee(104, "赵六", 8, 7777.77, Employee.Status.FREE),
new Employee(105, "田七", 38, 5555.55, Employee.Status.BUSY)
);
//终止操作
/**
* allMatch:检查是否匹配所有元素
* anyMatch:检查是否至少匹配一个元素
* noneMatch:检查是否没有匹配的元素
* findFirst:返回第一个元素
* findAny:返回当前流中的任意元素
* count:返回流中元素的总个数
* max:返回流中最大值
* min:返回流中最小值
*/
@Test
public void test1(){
//是否匹配所有元素
boolean b1 = emps.stream()
.allMatch((e) ->e.getStatus().equals(Employee.Status.BUSY));
System.out.println(b1);
//是否至少匹配一个元素
boolean b2 = emps.stream()
.anyMatch((e) -> e.getStatus().equals(Employee.Status.BUSY));
System.out.println(b2);
//检查是否没有匹配的元素
boolean b3 = emps.stream()
.noneMatch((e) -> e.getStatus().equals(Employee.Status.BUSY));
System.out.println(b3);
}
@Test
public void test2(){
//返回第一个元素。按工资排序
//Optional也是Java8中提供的新特性,防止空异常
//这里返回Optional只是它觉得有可能为空
Optional<Employee> optional = emps.stream()
.sorted((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()))
.findFirst();
System.out.println(optional.get());
System.out.println("----------------------------");
//返回当前流中的任意元素
Optional<Employee> any = emps.parallelStream()
.filter((e) -> e.getStatus().equals(Employee.Status.FREE))
.findAny();
System.out.println(any.get());
}
@Test
public void test3(){
//返回流中元素总个数
long count = emps.stream()
.filter((e) -> e.getStatus().equals(Employee.Status.FREE))
.count();
System.out.println(count);
System.out.println("---------------------");
//返回流中最大值
Optional<Double> max = emps.stream()
.map(Employee::getSalary)
.max(Double::compare);
System.out.println(max.get());
System.out.println("--------------------");
//返回流中最小值
Optional<Double> min = emps.stream()
.map(Employee::getSalary)
.min(Double::compare);
System.out.println(min.get());
}
/**
* 注意:
* 流进行了终止操作后,不能再使用,会报错
*/
@Test
public void test4(){
Stream<Employee> stream = emps.stream()
.filter((e) -> e.getStatus().equals(Employee.Status.FREE));
//终止stream流
long count = stream.count();
//再用一遍stream流,会发现报错
stream.map(Employee::getSalary)
.max(Double::compare);
}
}
注意:流进行了终止操作后,不能再使用,会报错。
方法 | 描述 |
---|---|
reduce(T iden,BinaryOperator b) | 可以将流中元素反复结合起来,得到一个值。 |
reduce(BinaryOperator b) | 可以将流中元素反复结合起来,得到一个值。返回Optional |
注意:map和reduce的连接通常称为map-reduce模式,因Google用它来进行网络搜索而出名。
List<Employee> emps = Arrays.asList(
new Employee(102, "李四", 79, 6666.66, Employee.Status.BUSY),
new Employee(101, "张三", 18, 9999.99, Employee.Status.FREE),
new Employee(103, "王五", 28, 3333.33, Employee.Status.VOCATION),
new Employee(104, "赵六", 8, 7777.77, Employee.Status.BUSY),
new Employee(104, "赵六", 8, 7777.77, Employee.Status.FREE),
new Employee(104, "赵六", 8, 7777.77, Employee.Status.FREE),
new Employee(105, "田七", 38, 5555.55, Employee.Status.BUSY));
//终止操作
/**
* 归约
* reduce(T identity,BinaryOperator) / reduce(BinaryOperator)可以将流中元素反复结合起来,得到一个值
*/
@Test
public void test1(){
List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
//求和操作
//reduce中参数,第一个值,初始值,之后x就是0,y是集合中的第一个值
//之后做相加的操作,得到的值又作为x的值,再取集合中第二个值作为y,求和
//以此类推
Integer sum = list.stream()
.reduce(0, (x, y) -> x + y);
System.out.println(sum);
System.out.println("-------------------");
//对Employee的salary列求和
//返回的值是Java8的新特性,防止空异常
//map指定要操作的列,reduce指定要进行的操作,这里写的是求和操作
Optional<Double> op = emps.stream()
.map(Employee::getSalary)
.reduce(Double::sum);
System.out.println(op.get());
}
//需求:搜索名字中"六"出现的次数
@Test
public void test2(){
/**
* emps.stream().map(Employee::getName) 具体看map讲解,这里可以理解拿到Employee的name值,所有的,返回一个流
* .flatMap(TestStreamAPI4::filterCharacter)即对上面操作生成的名字的流做了处理,取出字符串中的字符,最终返回一个Character流
* .map((ch) -> {再对character流进行处理,将每个字符和六比较,有就返回1,没有就返回0,这样会得到一个包含所有六次数的Integer流,可以想象成返回一个数组那样,给下一步处理
* .reduce(Integer::sum)最后再对这个Integer流做求和处理
*/
Optional<Integer> optional = emps.stream()
.map(Employee::getName)
.flatMap(TestStreamAPI4::filterCharacter)
.map((ch) -> {
if (ch.equals('六')) {
return 1;
} else {
return 0;
}
}).reduce(Integer::sum);
System.out.println(optional.get());
}
/**
* 自定义方法:接收一个字符串
* 取出字符串中的字符,添加至list集合中
* 返回list集合的stream流
*/
public static Stream<Character> filterCharacter(String str){
List<Character> list = new ArrayList<>();
for (Character ch : str.toCharArray()){
list.add(ch);
}
return list.stream();
}
方法 | 描述 |
---|---|
collect(Collector c) | 将流转换为其他形式。接收一个Collector接口的实现,用于给Stream中元素 |
方法 | 返回类型 | 作用 |
---|---|---|
toList | List | 把流中元素收集到List:List |
toSet | Set | 把流中元素收集到Set:Set |
toCollection | Collection | 把流中元素收集到创建的集合:Collection |
counting | Long | 计算流中元素的个数:long count = list.stream.collect(Collectors.counting()); |
summingInt | Integer | 对流中元素的整数属性求和:int total = list.stream().collect(Collectors.summingInt(Employee::getSalary)); |
averagingInt | Double | 计算流中元素Integer属性的平均值:double avg = list.stream().collect(Collectors.averagingInt(Employee::getSalay)); |
summarizingInt | IntSummaryStatistics | 收集流中Integer属性的统计值。如:平均值:IntSummaryStatiscs iss = list.stream().collect(Collectiors.summarizingInt(Empliyee::getSalary)); |
joining | String | 连接流中每个字符串:String str = list.stream().map(Employee::getName).collect(Collectors.joining()); |
maxBy | Optional | 根据比较器选择最大值:Optional |
minBy | Optional | 根据比较器选择最小值:Optional |
reducing | 归约产生的类型 | 从一个作为累加器的初始值开始,利用BinaryOperator与流中元素逐个结合,从而归约成单个值。int total = list.stream.collect(Collectors.reducing(0,Employee::getSalary,Integer::sum)); |
collectingAndThen | 转换函数返回的类型 | 包裹另一个收集器,对其结果转换函数:int how=list.stream().collect(Collectors.collectingAndThen(Collectors.toList(),List::size)); |
groupingBy | Map |
根据某属性值对流分组,属性为K,结果为V:Map |
partitioningBy | Map |
根据true或false进行分区:Map |
//collect将流转换为其他形式。接收一个Collector接口的实现,用于给Stream中元素做汇总的方法
@Test
public void test3(){
//将name属性所有值转成list集合
List<String> list = emps.stream()
.map(Employee::getName)
.collect(Collectors.toList());
list.forEach(System.out::println);
System.out.println("--------------------");
//将name属性所有值转成set集合
Set<String> set = emps.stream()
.map(Employee::getName)
.collect(Collectors.toSet());
set.forEach(System.out::println);
System.out.println("-------------------------");
//将name属性所有值转成指定的集合类型,这里指定HashSet
HashSet<String> hashSet = emps.stream()
.map(Employee::getName)
.collect(Collectors.toCollection(HashSet::new));
hashSet.forEach(System.out::println);
}
@Test
public void test4(){
//求工资最大值
Optional<Double> max = emps.stream()
.map(Employee::getSalary)
.collect(Collectors.maxBy(Double::compare));
System.out.println(max.get());
System.out.println("-----------------------");
//求工资最小
Optional<Employee> min = emps.stream()
.collect(Collectors.minBy((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())));
System.out.println(min.get());
System.out.println("------------------------");
//求工资和
Double sum = emps.stream()
.collect(Collectors.summingDouble(Employee::getSalary));
System.out.println(sum);
System.out.println("-----------------------");
Double avg = emps.stream()
.collect(Collectors.averagingDouble(Employee::getSalary));
System.out.println(avg);
Long count = emps.stream()
.collect(Collectors.counting());
System.out.println(count);
System.out.println("--------------------------------------------");
DoubleSummaryStatistics dss = emps.stream()
.collect(Collectors.summarizingDouble(Employee::getSalary));
System.out.println(dss.getMax());
}
//分组
@Test
public void test5(){
//按状态分组
Map<Employee.Status, List<Employee>> map = emps.stream()
.collect(Collectors.groupingBy(Employee::getStatus));
System.out.println(map);
}
//多级分组
@Test
public void test6(){
Map<Employee.Status, Map<String, List<Employee>>> map = emps.stream()
.collect(Collectors.groupingBy(Employee::getStatus, Collectors.groupingBy((e) -> {
if (e.getAge() >= 60) {
return "老年";
} else if (e.getAge() >= 35) {
return "中年";
} else {
return "成年";
}
}
)));
System.out.println(map);
}
//分区
@Test
public void test7(){
Map<Boolean, List<Employee>> map = emps.stream()
.collect(Collectors.partitioningBy((e) -> e.getSalary() >= 5000));
System.out.println(map);
}
//连接流中字符串
@Test
public void test8(){
String collect = emps.stream()
.map(Employee::getName)
//第一个参数指定参数间的连接字符,第二个参数指定首的连接符,第三个参数指定尾的连接符。二三参数可以不指定
.collect(Collectors.joining(",", "---", "---"));
System.out.println(collect);
}
@Test
public void test9(){
Optional<Double> sum = emps.stream()
.map(Employee::getSalary)
.collect(Collectors.reducing(Double::sum));
System.out.println(sum.get());
}
parallel()
与sequential()
在并行流与顺序流之间进行切换。[外链图片转存失败(img-o0WWXMIy-1563864715861)(en-resource://database/550:1)]
//继承RecursiveTask类,自己实现Fork/Join,其实就是写算法,如何拆分子任务
package com.wangwren.stream;
import java.util.concurrent.RecursiveTask;
/**
* @author: wangwren
* @date: 2019/4/6
* @descripton: 要计算0至一亿的和,自己先使用fork/join实现一下
* RecursiveTask是带有返回值的,RecursiveAction不带有返回值
* Recursive的意思是“递归”
* @version: 1.0
*/
public class ForkJoinCalcuate extends RecursiveTask<Long> {
private long start;
private long end;
//临界值,设为一万,即小任务中包含一万个数
private static final long THRESHOLD = 10000L;
public ForkJoinCalcuate(long start,long end){
this.start = start;
this.end = end;
}
@Override
protected Long compute() {
long length = end - start;
if (length <= THRESHOLD){
long sum = 0;
//循环相加
for (long i = start;i <= end;i++){
sum += i;
}
return sum;
}else{
//对任务进行拆分
long middle = (start + end) / 2;
ForkJoinCalcuate left = new ForkJoinCalcuate(start,middle);
//拆分,并将该子任务压入线程队列
//fork是ForkJoinTask提供的方法
left.fork();
ForkJoinCalcuate right = new ForkJoinCalcuate(middle + 1,end);
right.fork();
//合并
return left.join() + right.join();
}
}
}
package com.wangwren.stream;
import org.junit.Test;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;
/**
* @author: wangwren
* @date: 2019/4/6
* @descripton:
* @version: 1.0
*/
public class ForkJoinTest {
/**
* 检验自己实现的fork/join
*
* test1与test2相比,在一亿个数的情况下,2的时间短,所以fork/join应该使用在数量级更大的情况
* 此时增加数量级
*/
@Test
public void test1(){
long startTime = System.currentTimeMillis();
//创建一个Fork/Join池
ForkJoinPool pool = new ForkJoinPool();
ForkJoinTask<Long> task = new ForkJoinCalcuate(0,10000000000L);
//执行任务
Long sum = pool.invoke(task);
System.out.println(sum);
long endTime = System.currentTimeMillis();
System.out.println("耗费时间:" + (endTime - startTime));
}
/**
* 使用普通for循环方式来计算,比较二者时间
*/
@Test
public void test2(){
long startTime = System.currentTimeMillis();
long sum = 0L;
for (long i = 0 ; i <= 10000000000L ; i ++ ){
sum += i;
}
System.out.println(sum);
long endTime = System.currentTimeMillis();
System.out.println("消耗时间:" + (endTime - startTime));
}
/**
* Java8提供的并行流
*/
@Test
public void test3(){
long startTime = System.currentTimeMillis();
long sum = LongStream.rangeClosed(0, 10000000000L)
//使用并行流
.parallel()
.sum();
System.out.println(sum);
long endTime = System.currentTimeMillis();
System.out.println("消耗时间:" + (endTime - startTime));
}
}
// 使用一个容器装载 100 个数字,通过 Stream 并行处理的方式将容器中为单数的数字转移到容器 parallelList
List<Integer> integerList= new ArrayList<Integer>();
for (int i = 0; i <100; i++) {
integerList.add(i);
}
List<Integer> parallelList = new ArrayList<Integer>() ;
integerList.stream()
.parallel()
.filter(i->i%2==1)
.forEach(i->parallelList.add(i));
collect()
。关于collect()
,文章中已经提到过了,可以上翻看一下,是终止操作里的,可以使用collect()
重新生成一个List集合。当应用程序以前没有使用lambda表达式时,会动态生成lambda目标对象,这是导致慢的实际原因。
虽然单独使用lambda表达式在初次运行时要比传统方式慢很多,但结合stream的并行操作,在多核环境下还有有优势的。