前言
在我们工作日常中经常需要对数据集合进行处理,Java8 的Stream API可以极大提高Java程序员的生产力,让程序员写出高效率、干净、简洁的代码。
这种风格将要处理的元素集合看作一种流, 流在管道中传输, 并且可以在管道的节点上进行处理, 比如筛选, 排序,聚合等。
元素流在管道中经过中间操作(intermediate operation)的处理,最后由最终操作(terminal operation)得到前面处理的结果。。
什么是stream流?
我们来看看源码是如何定义的:
/**
* Returns a sequential {@code Stream} with this collection as its source.
*
*
* <p>This method should be overridden when the {@link #spliterator()}
* method cannot return a spliterator that is {@code IMMUTABLE},
* {@code CONCURRENT}, or <em>late-binding</em>. (See {@link #spliterator()}
* for details.)
*
* @implSpec
* The default implementation creates a sequential {@code Stream} from the
* collection's {@code Spliterator}.
*
* @return a sequential {@code Stream} over the elements in this collection
* @since 1.8
*/
default Stream<E> stream() {
return StreamSupport.stream(spliterator(), false);
可以简单理解为:支持数据处理操作的源生成的元素序列
下面我们对这个概念进行详细解剖:
- 元素序列:就像集合一样,流也提供了一个接口,可以访问特定元素类型的一组有序值。因为集合是数据结构,所以它的主要目的是以特定的时间/空间复杂度存储和访问元素(如ArrayList 与 LinkedList)。但流的目的在于表达计算,比如filter、 sorted和map。集合讲的是数据,流讲的是计算。
- 源:流会使用一个提供数据的源,如集合、数组或输入/输出资源。 请注意,从有序集合生成流时会保留原有的顺序。由列表生成的流,其元素顺序与列表一致。
- 数据处理操作:流的数据处理功能支持类似于数据库的操作,以及函数式编程语言中的常用操作,如filter、 map、 reduce、 find、 match、 sort等。流操作可以顺序执行,也可并行执行。
- 流水线:很多流操作本身会返回一个流,这样多个操作就可以链接起来,形成一个大的流水线,流水线的操作可以看作对数据源进行数据库式查询。
- 内部迭代:与使用迭代器显式迭代的集合不同,流的迭代操作是在背后进行的。
1.如何创建一个stream流
我们可以通过一下几种方式来创建stream流
//1.Stream可以通过集合创建
List<User> list = userService.list(null);
//1.1创建一个顺序流
Stream<User> stream1 = list.stream();
//1.1创建一个并行流
Stream<User> userStream = list.parallelStream();
//2.使用java.util.Arrays.stream(T[] array)方法用数组创建流
int[] array={1,2,3,4,5};
IntStream stream2 = Arrays.stream(array);
//3.使用Stream的静态方法:of()、iterate()、generate()
Stream<Integer> stream3 = Stream.of(1, 2, 3, 4, 5, 6);
Stream<Integer> stream4 = Stream.iterate(0, (x) -> x + 3).limit(4);
stream2.forEach(System.out::println); // 0 2 4 6 8 10
Stream<Double> stream5 = Stream.generate(Math::random).limit(3);
stream3.forEach(System.out::println);
这里解释下parallelStream
简单理解就是多线程异步任务的一种实现。Stream具有平行处理能力,处理的过程会分而治之,也就是将一个大任务切分成多个小任务,这表示每个任务都是一个操作。
2.Stream流的常用方法
为了测试方便我们先在测试代码块创建一个list集合
static List<Person> personList = new ArrayList<Person>();{
personList.add(new Person("Tom", 8900,23, "male", "New York"));
personList.add(new Person("Jack", 7000, 34,"male", "Washington"));
personList.add(new Person("Lily", 7800, 24,"female", "Washington"));
personList.add(new Person("Anni", 8200, 32,"female", "New York"));
personList.add(new Person("Owen", 3000,95, "male", "New York"));
personList.add(new Person("Alisa", 4300,79, "female", "New York"));
}
2.1 forEach遍历
@Test
public void foreachTest(){
personList.stream().forEach(System.out::println);
//输出结果:Person(name=Tom, salary=8900, age=23, sex=male, area=New York)
//Person(name=Jack, salary=7000, age=34, sex=male, area=Washington)
//Person(name=Lily, salary=7800, age=24, sex=female, area=Washington)
//Person(name=Anni, salary=8200, age=32, sex=female, area=New York)
//Person(name=Owen, salary=3000, age=95, sex=male, area=New York)
//Person(name=Alisa, salary=4300, age=79, sex=female, area=New York)
}
2.2 filter过滤
@Test
public void filterTest(){
//过滤出age>30的
personList.stream().filter(person -> person.getAge() > 30).forEach(System.out::println);
//输出结果:Person(name=Jack, salary=7000, age=34, sex=male, area=Washington)
//Person(name=Anni, salary=8200, age=32, sex=female, area=New York)
//Person(name=Owen, salary=30, age=9500, sex=male, area=New York)
//Person(name=Alisa, salary=43, age=7900, sex=female, area=New York)
//过滤出age>30的,第一个结果,findFirst()
// findAny()返回任意一个结果,可自行测试
Person person1 = personList.parallelStream().filter(person -> person.getAge() > 30).findAny().get();
System.out.println(person1);
//结果:Person(name=Anni, salary=8200, age=32, sex=female, area=New York)
}
2.3distinct 去重
@Test
public void distinctTest(){
personList.add(new Person("Alisa", 4300,79, "female", "New York"));
personList.stream().forEach(System.out::println);
//结果:可以看到最后两行重复
//Person(name=Tom, salary=8900, age=23, sex=male, area=New York)
//Person(name=Jack, salary=7000, age=34, sex=male, area=Washington)
//Person(name=Lily, salary=7800, age=24, sex=female, area=Washington)
//Person(name=Anni, salary=8200, age=32, sex=female, area=New York)
//Person(name=Owen, salary=3000, age=95, sex=male, area=New York)
//Person(name=Alisa, salary=4300, age=79, sex=female, area=New York)
//Person(name=Alisa, salary=4300, age=79, sex=female, area=New York)
personList.stream().distinct().forEach(System.out::println);
//结果:重复去除
//Person(name=Tom, salary=8900, age=23, sex=male, area=New York)
//Person(name=Jack, salary=7000, age=34, sex=male, area=Washington)
//Person(name=Lily, salary=7800, age=24, sex=female, area=Washington)
//Person(name=Anni, salary=8200, age=32, sex=female, area=New York)
//Person(name=Owen, salary=3000, age=95, sex=male, area=New York)
//Person(name=Alisa, salary=4300, age=79, sex=female, area=New York)
}
2.3 sorted排序
@Test
public void sortedTest(){
personList.stream()
.sorted(Comparator.comparingInt(Person :: getAge))
.forEach(System.out::println);
//结果
//Person(name=Tom, salary=8900, age=23, sex=male, area=New York)
//Person(name=Lily, salary=7800, age=24, sex=female, area=Washington)
//Person(name=Anni, salary=8200, age=32, sex=female, area=New York)
//Person(name=Jack, salary=7000, age=34, sex=male, area=Washington)
//Person(name=Alisa, salary=4300, age=79, sex=female, area=New York)
//Person(name=Owen, salary=3000, age=95, sex=male, area=New York)
//倒排序用.reversed()
personList.stream()
.sorted(Comparator.comparingInt(Person :: getAge).reversed())
.forEach(System.out::println);
//结果
//Person(name=Owen, salary=3000, age=95, sex=male, area=New York)
//Person(name=Alisa, salary=4300, age=79, sex=female, area=New York)
//Person(name=Jack, salary=7000, age=34, sex=male, area=Washington)
//Person(name=Anni, salary=8200, age=32, sex=female, area=New York)
//Person(name=Lily, salary=7800, age=24, sex=female, area=Washington)
//Person(name=Tom, salary=8900, age=23, sex=male, area=New York)
}
2.4统计个数count()
@Test
public void countTest(){
long count = personList.stream().count();
System.out.println(count);
//结果:6
}
2.5取用前几个limit()
@Test
public void limitTest(){
personList.stream().limit(3).forEach(System.out::println);
//结果
//Person(name=Tom, salary=8900, age=23, sex=male, area=New York)
//Person(name=Jack, salary=7000, age=34, sex=male, area=Washington)
//Person(name=Lily, salary=7800, age=24, sex=female, area=Washington)
}
2.6跳过前几个skip()
@Test
public void skipTest(){
personList.stream().skip(5).forEach(System.out::println);
//结果Person(name=Alisa, salary=4300, age=79, sex=female, area=New York)
}
2.7合并concat()
@Test
public void concatTest(){
List<Person> personList1 = new ArrayList<Person>();
personList1.add(new Person("lisi", 10000,45, "male", "beijing"));
personList1.add(new Person("wangwu", 7653,32, "female", "New York"));
Stream<Person> stream = personList.stream();
Stream<Person> stream1 = personList1.stream();
Stream.concat(stream,stream1).forEach(System.out::println);
//结果
//Person(name=Tom, salary=8900, age=23, sex=male, area=New York)
//Person(name=Jack, salary=7000, age=34, sex=male, area=Washington)
//Person(name=Lily, salary=7800, age=24, sex=female, area=Washington)
//Person(name=Anni, salary=8200, age=32, sex=female, area=New York)
//Person(name=Owen, salary=3000, age=95, sex=male, area=New York)
//Person(name=Alisa, salary=4300, age=79, sex=female, area=New York)
//Person(name=lisi, salary=10000, age=45, sex=male, area=beijing)
//Person(name=wangwu, salary=7653, age=32, sex=female, area=New York)
}
2.8map(T->R)可以将一个流的元素按照一定的映射规则映射到另一个流中
@Test
public void mapTest(){
//把所有人工资加10000
//方式一:改变原集合
List<Person> personNewList1 = personList.stream().map((person) -> {
person.setSalary(person.getSalary()+10000);
return person;
}).collect(Collectors.toList());
System.out.println("加工资之后");
personList.stream().forEach(System.out::println);
//结果
//加工资之后
//Person(name=Tom, salary=18900, age=23, sex=male, area=New York)
//Person(name=Jack, salary=17000, age=34, sex=male, area=Washington)
//Person(name=Lily, salary=17800, age=24, sex=female, area=Washington)
//Person(name=Anni, salary=18200, age=32, sex=female, area=New York)
//Person(name=Owen, salary=13000, age=95, sex=male, area=New York)
//Person(name=Alisa, salary=14300, age=79, sex=female, area=New York)
//方式一:不改变原集合
List<Person> personNewList = personList.stream().map((person) -> {
//Person personNew = new Person(person.getName(), 0, person.getAge(), person.getSex(), person.getArea());
Person personNew = new Person();
BeanUtils.copyProperties(person,personNew);
personNew.setSalary(person.getSalary() + 10000);
return personNew;
}).collect(Collectors.toList());
System.out.println("加工资之前");
personList.stream().forEach(System.out::println);
System.out.println();
System.out.println("加工资之后");
personNewList.stream().forEach(System.out::println);
//结果
//加工资之前
//Person(name=Tom, salary=8900, age=23, sex=male, area=New York)
//Person(name=Jack, salary=7000, age=34, sex=male, area=Washington)
//Person(name=Lily, salary=7800, age=24, sex=female, area=Washington)
//Person(name=Anni, salary=8200, age=32, sex=female, area=New York)
//Person(name=Owen, salary=3000, age=95, sex=male, area=New York)
//Person(name=Alisa, salary=4300, age=79, sex=female, area=New York)
//加工资之后
//Person(name=Tom, salary=18900, age=23, sex=male, area=New York)
//Person(name=Jack, salary=17000, age=34, sex=male, area=Washington)
//Person(name=Lily, salary=17800, age=24, sex=female, area=Washington)
//Person(name=Anni, salary=18200, age=32, sex=female, area=New York)
//Person(name=Owen, salary=13000, age=95, sex=male, area=New York)
//Person(name=Alisa, salary=14300, age=79, sex=female, area=New York)
}
2.9 reduce()
Reduce中文含义为:减少、缩小;而Stream中的Reduce方法干的正是这样的活:根据一定的规则将Stream中的元素进行计算后返回一个唯一的值。
@Test
public void reduceTest(){
//求所有员工的工资之和和最高工资
Optional<Integer> sumSalary = personList.stream().map(Person::getSalary).reduce(Integer::sum);
// 求工资之和方式2:
Integer sumSalary2 = personList.stream().reduce(0, (sum, p) -> sum += p.getSalary(),
(sum1, sum2) -> sum1 + sum2);
// 求工资之和方式3:
Integer sumSalary3 = personList.stream().reduce(0, (sum, p) -> sum += p.getSalary(), Integer::sum);
// 求最高工资方式1:
Integer maxSalary = personList.stream().reduce(0, (max, p) -> max > p.getSalary() ? max : p.getSalary(),
Integer::max);
// 求最高工资方式2:
Integer maxSalary2 = personList.stream().reduce(0, (max, p) -> max > p.getSalary() ? max : p.getSalary(),
(max1, max2) -> max1 > max2 ? max1 : max2);
System.out.println("工资之和:" + sumSalary.get() + "," + sumSalary2 + "," + sumSalary3);
System.out.println("最高工资:" + maxSalary + "," + maxSalary2);
//结果
//工资之和:39200,39200,39200
//最高工资:8900,8900
}
2.10 收集(collect),收集,可以说是内容最繁多、功能最丰富的部分了
从字面上去理解,就是把一个流收集起来,最终可以是收集成一个值也可以收集成一个新的集合
@Test
protected void collectTest(){
//把age全部改为18,用collection收集成新的list集合
personList.stream().map((person)->{
person.setAge(18);
return person;
}).collect(Collectors.toList()).forEach(System.out::println);
//结果
//Person(name=Tom, salary=8900, age=18, sex=male, area=New York)
//Person(name=Jack, salary=7000, age=18, sex=male, area=Washington)
//Person(name=Lily, salary=7800, age=18, sex=female, area=Washington)
//Person(name=Anni, salary=8200, age=18, sex=female, area=New York)
//Person(name=Owen, salary=3000, age=18, sex=male, area=New York)
//Person(name=Alisa, salary=4300, age=18, sex=female, area=New York)
// ps:类似的还有toSet和toMap,大家可自行测试
}
2.11统计(count/averaging)
Collectors提供了一系列用于数据统计的静态方法:
计数:count
平均值:averagingInt、averagingLong、averagingDouble
最值:maxBy、minBy
求和:summingInt、summingLong、summingDouble
统计以上所有:summarizingInt、summarizingLong、summarizingDouble
//案例:统计员工人数、平均工资、工资总额、最高工资。
@Test
public void salaryTest(){
// 求总数
Long count = personList.stream().collect(Collectors.counting());
// 求平均工资
Double average = personList.stream().collect(Collectors.averagingDouble(Person::getSalary));
// 求最高工资
Optional<Integer> max = personList.stream().map(Person::getSalary).collect(Collectors.maxBy(Integer::compare));
// 求工资之和
Integer sum = personList.stream().collect(Collectors.summingInt(Person::getSalary));
// 一次性统计所有信息
DoubleSummaryStatistics collect = personList.stream().collect(Collectors.summarizingDouble(Person::getSalary));
System.out.println("员工总数:" + count);
System.out.println("员工平均工资:" + average);
System.out.println("员工最高工资:"+max.get());
System.out.println("员工工资总和:" + sum);
System.out.println("员工工资所有统计:" + collect);
//结果
//员工总数:6
//员工平均工资:6533.333333333333
//员工最高工资:8900
//员工工资总和:39200
//员工工资所有统计:DoubleSummaryStatistics{count=6, sum=39200.000000, min=3000.000000, average=6533.333333, max=8900.000000}
}
2.12分组(partitioningBy/groupingBy)
分区:将stream按条件分为两个Map,比如员工按薪资是否高于8000分为两部分。
分组:将集合分为多个Map,比如员工按性别分组。有单级分组和多级分组。
@Test
public void groupTest(){
// 将员工按薪资是否高于8000分组
Map<Boolean, List<Person>> part = personList.stream().collect(Collectors.partitioningBy(x -> x.getSalary() > 8000));
// 将员工按性别分组
Map<String, List<Person>> group = personList.stream().collect(Collectors.groupingBy(Person::getSex));
// 将员工先按性别分组,再按地区分组
Map<String, Map<String, List<Person>>> group2 = personList.stream().collect(Collectors.groupingBy(Person::getSex, Collectors.groupingBy(Person::getArea)));
System.out.println("员工按薪资是否大于8000分组情况:" + part);
System.out.println("员工按性别分组情况:" + group);
System.out.println("员工按性别、地区:" + group2);
//结果
//员工按薪资是否大于8000分组情况:{false=[Person(name=Jack, salary=7000, age=34, sex=male, area=Washington), Person(name=Lily, salary=7800, age=24, sex=female, area=Washington), Person(name=Owen, salary=3000, age=95, sex=male, area=New York), Person(name=Alisa, salary=4300, age=79, sex=female, area=New York)], true=[Person(name=Tom, salary=8900, age=23, sex=male, area=New York), Person(name=Anni, salary=8200, age=32, sex=female, area=New York)]}
//员工按性别分组情况:{female=[Person(name=Lily, salary=7800, age=24, sex=female, area=Washington), Person(name=Anni, salary=8200, age=32, sex=female, area=New York), Person(name=Alisa, salary=4300, age=79, sex=female, area=New York)], male=[Person(name=Tom, salary=8900, age=23, sex=male, area=New York), Person(name=Jack, salary=7000, age=34, sex=male, area=Washington), Person(name=Owen, salary=3000, age=95, sex=male, area=New York)]}
//员工按性别、地区:{female={New York=[Person(name=Anni, salary=8200, age=32, sex=female, area=New York), Person(name=Alisa, salary=4300, age=79, sex=female, area=New York)], Washington=[Person(name=Lily, salary=7800, age=24, sex=female, area=Washington)]}, male={New York=[Person(name=Tom, salary=8900, age=23, sex=male, area=New York), Person(name=Owen, salary=3000, age=95, sex=male, area=New York)], Washington=[Person(name=Jack, salary=7000, age=34, sex=male, area=Washington)]}}
}
2.13接合(joining)
@Test
public void joiningTest(){
String names = personList.stream().map(p -> p.getName()).collect(Collectors.joining(","));
System.out.println("所有员工的姓名:" + names);
List<String> list = Arrays.asList("A", "B", "C");
String string = list.stream().collect(Collectors.joining("-"));
System.out.println("拼接后的字符串:" + string);
//结果
//所有员工的姓名:Tom,Jack,Lily,Anni,Owen,Alisa
//拼接后的字符串:A-B-C
}
总结
以上就是全部内容啦,有些介绍的可能还不够详细,但是上面案例只要跟着敲一遍。相信你一定会有所收获。