目录
Java8中有两大最为重要的改变。第一个是Lambda表达式; 另外一个则是Stream API。
Stream API ( java.util.stream) 把真正的函数式编程风格引入到Java中。这是目前为止对Java类库最好的补充,因为Stream API可以极大提供Java程序员的生产力,让程序员写出高效率、干净、简洁的代码。
Stream是Java8中处理集合的关键抽象概念,它可以指定你希望对集合进行的操作,可以执行非常复杂的查找、过滤和映射数据等操作。使用Stream API对集合数据进行操作,就类似于使用SQL执行的数据库查询。也可以使用Stream API来并行执行操作。简言之,Stream API提供了一种高效且易于使用的处理数据的方式。
一、为什么使用stream api
1.1 基本介绍
实际开发中,项目中多数数据源都来自于Mysq|,Oracle等。 但现在数据源可以更多了,有MongDB,Radis等,而这些NoSQL的数据就需要Java层面去处理。
java8中的stream与InputStream和OutputStream是完全不同的概念,stream是用于对集合迭代器
的增强,使之完成能够完成更高效的聚合操作(过滤、排序、统计分组)或者大批量数据操作。
此外与stream与lambada表达示结合后编码效率与大大提高,且可读性更强。
1.2 代码示例
public class AppleServer {
private static List<Apple> appleStore = new ArrayList<>();
static {
appleStore.add(new Apple("red", 1));
appleStore.add(new Apple("red", 2));
appleStore.add(new Apple("green", 3));
appleStore.add(new Apple("yellow", 4));
appleStore.add(new Apple("red", 5));
}
public void test1() {
for (Apple apple : appleStore) {
if (apple.getColor().equals("red")) {
//add
}
}
}
public void test2() {
List<Apple> list = appleStore.stream()
.filter(a -> a.getColor().equals("red"))
.collect(Collectors.toList());
}
@Test
public void test3() {
//计算每种颜色苹果的个数以及平均重量
appleStore.stream()
.collect(Collectors.groupingBy(a -> a.getColor(),
Collectors.averagingInt(a -> a.getWeight())))
.forEach((k, v) -> System.out.println(k + ":" + v));
}
}
@AllArgsConstructor
@Data
class Apple {
private String color;
private int weight;
}
注意:
- ① Stream自己不会存储元素。不可重复使用
public void test2() { List<Apple> list = appleStore.stream() .filter(a -> a.getColor().equals("red")) .collect(Collectors.toList()); }
- ② Stream不会改变源对象。相反,他们会返回一个持有结果的新Stream.
- ③ Stream操作是延迟执行的。这意味着他们会等到需要结果的时候才执行。
1.3 常用API以及使用场景
二、stream擅长解决的问题
遍历在传统的javaEE项目中数据源比较单而且集中,像这类的需求都我们可能通过关系数据库中进行获取计算。
但现在的互联网项目数据源成多样化有:关系数据库、NoSQL、Redis、mongodb、ElasticSearch、 Cloud Server等。这时就需我们从各数据源中汇聚数据并进行统计。这在Stream出现之前只能过遍历实现非常繁琐。
2.1 场景一: 跨库join的问题
查询一个店铺的订单信息,需要用到订单表与会员表在传统数据库单一例中,可以通过jon关联轻松实现,但在分布场景中这两张表分别存储在于交易库和会员库两个实例中,join不能用。
只能在服务端实现其流程如下:
- 1. 查询订单表数据
- 2.找出订单中所有会员的ID
- 3.根据会员ID查询会员表信息
- 4.将订单数据与会员数据进行合并
这用传统迭代方法非常繁琐,而这正是stream所擅长的。示例代码如下:
// 获取所有会员ID 并去重
List<Integer> ids = orders
.stream()
.map(o -> o.getMemberId())
.distinct()
.collect(Collectors.toList());
// 合并会员信息 至订单信息
orders.stream().forEach(o -> {
Member member = members
.stream()
.filter(m -> m.getId() == o.getMemberId()).findAny().get();
o.setMemberName(member.getName());});
2.2 场景二:N+1 问题
三、 Stream和Collection集合的区别:
- Collection 是一种静态的内存数据结构,主要面向内存,存储在内存中
- Stream是有关计算的,主要是面向CPU,通过CPU实现计算。
3.1 stream的操作三个步骤——流的执行过程
1 创建Stream
一个数据源(如:集合、数组),获取一个流
2 中间操作
一个中间操作链,对数据源的数据进行处理
3 终止操作(终端操作)
一旦执行终止操作,就执行中间操作链,并产生结果。之后,不会再被使用
四、 并行流与串行流
并行流就是把一个内容分成多个数据块,并用不同的线程分别处理每个数据块的流。相比较串行的流,并行的流可以很大程度上提高程序的执行效率。
Java 8中将并行进行了优化,我们可以很容易的对数据进行并行操作。Stream API可以声明性地通过parallel() 与sequential()在并行流与顺序流之间进行切换。
五、 Stream实例化
5.1 创建Stream方式一: 通过集合
Java8中的Collection接口被扩展,提供了两个获取流的方法:
- default Stream<E> stream() —— 返回一个顺序流
- default Stream<E> parallelStream() —— 返回一个并行流
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Employee {
public String name;
public Integer age;
public static List<Employee> getEmployee() {
List<Employee> list = new ArrayList<>();
list.add(new Employee("name", 5));
return list;
}
}
public class StreamAPITest {
@Test
public void test1() {
List<Employee> employees = Employee.getEmployee();
//default Stream<E> stream() :返回一个顺序流.顺序流按照顺序获取数据
Stream<Employee> stream = employees.stream();
//default Stream<E> parallelStream():返回一个并行流,并不一定按照顺序获取数据
Stream<Employee> parallelStream = employees.parallelStream();
}
}
5.2 创建Stream方式二:通过数组
Java8中的Arrays的静态方法stream()可以获取数组流 :
- static <T> Stream<T> stream(T[] array):返回一个流
重载形式,能够处理对应基本类型的数组:
- public static IntStream stream(int[] array)
- public static LongStream stream(long[] array)
- public static DoubleStream stream(double[] array)
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Employee {
public String name;
public Integer age;
public static List<Employee> getEmployee() {
List<Employee> list = new ArrayList<>();
list.add(new Employee("name", 5));
return list;
}
}
public class StreamAPITest {
@Test
public void test2() {
int[] arr = new int[]{1, 2, 3, 4, 5, 6};
//调用Arrays,类的static <T> Stream<T> stream(T[] array): 返回一个流
IntStream stream = Arrays.stream(arr);
Employee e1 = new Employee("Tom", 2);
Employee e2 = new Employee("Jerry", 3);
Employee[] arr1 = new Employee[]{e1, e2};
Stream<Employee> stream1 = Arrays.stream(arr1);
}
}
5.3 创建Stream方式三,通过Stream的of()
可以调用Stream类静态方法of(),通过显示值创建一个流。它可以接收任意数量的参数。
- public static<T> Stream<T> of(T... values):返回一个流
@Test
public void test3() {
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6);
}
六、stream的中间操作——惰性求值
多个中间操作可以连接起来形成一个流水线,除非流水线上触发终止操作,否则中间操作不会执行任何的处理,而在终止操作时一次性全部处理,称为“惰性求值”。
6.1 筛选与切片
练习:查询员工年龄大于35岁的员工
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Employee {
public String name;
public Integer age;
public static List<Employee> getEmployee() {
List<Employee> list = new ArrayList<>();
list.add(new Employee("TOM", 5));
list.add(new Employee("TOM", 5));
list.add(new Employee("TOM", 5));
list.add(new Employee("TOM", 5));
list.add(new Employee("TOM", 5));
list.add(new Employee("JIRA", 45));
return list;
}
public class StreamAPITest {
@Test
public void test1() {
List<Employee> employees = Employee.getEmployee();
// default Stream<E> stream() :返回一个顺序流
Stream<Employee> stream = employees.stream();
//filter 接收Lambda ,从流中排除某些元素。
stream.filter(e -> e.getAge() > 35).forEach(System.out::println);
System.out.println("----------------------------------------------");
//limit 截断流,使其元素不超过给定数量。
employees.stream().limit(1).forEach(System.out::println);
System.out.println("----------------------------------------------");
//skip 跳过元素,返回一个扔掉了前n个元素的流
employees.stream().skip(5).forEach(System.out::println);
System.out.println("----------------------------------------------");
//distinct()-筛选,通过流所生成元素的hashCode()和equals()去除重复元素
employees.stream().distinct().forEach(System.out::println);
System.out.println("----------------------------------------------");
}
}
6.2 映射——美团面试问过
map类似于list的add方法;flatMap类似于list里的addAll方法
代码示例
public class StreamAPITest {
@Test
public void test2() {
//map(Function f) - 接收一个函数作为参数,将元素转换成其他形式或提取信息
List<String> list = Arrays.asList("aa", "bb");
list.stream().map(String::toUpperCase).forEach(System.out::println);
System.out.println("---------------------------------------------");
Stream<Stream<Character>> streamStream = list.stream().
map(StreamAPITest::fromStringToStream);
streamStream.forEach(
s -> {
s.forEach(System.out::println);
}
);
System.out.println("---------------------------------------------");
// fLatMap(Function f)- 接收一 个函数作为参数,将流中的每个值都换成另一个流
Stream<Character> characterStream = list.stream().
flatMap(StreamAPITest::fromStringToStream);
characterStream.forEach(System.out::println);
System.out.println("---------------------------------------------");
}
//将字符串中的多个字符构成的集合转换为对应的Stream的实例
public static Stream<Character> fromStringToStream(String str) {
ArrayList<Character> list = new ArrayList<>();
for (Character c : str.toCharArray()) {
list.add(c);
}
return list.stream();
}
}
6.3 排序
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Employee {
public String name;
public Integer age;
public static List<Employee> getEmployee() {
List<Employee> list = new ArrayList<>();
list.add(new Employee("TOM", 5));
list.add(new Employee("TOM", 5));
list.add(new Employee("TOM", 5));
list.add(new Employee("TOM", 5));
list.add(new Employee("TOM", 5));
list.add(new Employee("JIRA", 45));
return list;
}
}
@Test
public void test4() {
// sorted()-自然排序
List<Integer> list = Arrays.asList(12, 43, 65, 34, 87, 0, -98, 7);
list.stream().sorted().forEach(System.out::println);
List<Employee> employee = Employee.getEmployee();
employee.stream().sorted(
(e1, e2) -> Integer.compare(e1.getAge(), e2.getAge())).
forEach(System.out::println);
}
七、stream的终止操作
终端操作会从流的流水线生成结果。其结果可以是任何不是流的值,例如: List、 Integer, 甚至是void。
流进行了终止操作后,不能再次使用。
7.1 匹配与查找
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Employee {
public String name;
public Integer age;
public static List<Employee> getEmployee() {
List<Employee> list = new ArrayList<>();
list.add(new Employee("TOM", 5));
list.add(new Employee("TOM", 5));
list.add(new Employee("TOM", 5));
list.add(new Employee("TOM", 5));
list.add(new Employee("TOM", 5));
list.add(new Employee("JIRA", 45));
return list;
}
}
public class StreamAPITest {
//1-匹配与查找
@Test
public void test3() {
List<Employee> employees = Employee.getEmployee();
// allMatch(Predicate p)一检查是否匹配所有元素。
// 练习:是否所有的员工的年龄都大于18
boolean allMatch = employees.stream().allMatch(e -> e.getAge() > 18);
System.out.println(allMatch);
System.out.println("-------------------------------------");
// anyMatch(Predicate p)一检查是 否至少匹配-一个元素。
// 练习:是否存在员工的工资大于10000
System.out.println(employees.stream().anyMatch(e -> e.getAge() > 10000));
System.out.println("-------------------------------------");
// noneMatch(Predicate p)-检查是否没有匹配的元素。
// 练习:是否存在员工姓雷
boolean noneMatch = employees.stream().noneMatch(e -> e.getName().
startsWith("雷"));
System.out.println(noneMatch);
System.out.println("-------------------------------------");
// findFirst-返回第一个元素
Optional<Employee> employee = employees.stream().findFirst();
System.out.println(employee);
System.out.println("-------------------------------------");
// findAny-返回当前流 中的任意元素
Optional<Employee> employee1 = employees.parallelStream().findAny();
System.out.println(employee1);
System.out.println("-------------------------------------");
//count-返回流 中元素的总个数
long count = employees.stream().filter(e -> e.getAge() > 5000).count();
System.out.println(count);
System.out.println("-------------------------------------");
// max(Comparator c)一返回流中最大值
// 练习:返回最高的工资:
Stream<Integer> ageStream = employees.stream().map(Employee::getAge);
Optional<Integer> maxAge = ageStream.max(Integer::compare);
System.out.println(maxAge);
System.out.println("-------------------------------------");
}
}
7.2 归约
备注:
map和reduce的连接通常称为map-reduce模式,因Google用它来进行网络搜索而出名。
@Test
public void test5() {
//reduce( T identity, BinaryOperator
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
System.out.println(list.stream().reduce(0, Integer::sum));
//reduce(BinaryOperator)一可以将流中元素反复结合起来, 得到一个值。返回Optiond
// 练习2:计算公司所有员工年龄的总和
List<Employee> employees = Employee.getEmployee();
Stream<Integer> ageStream = employees.stream().map(Employee::getAge);
Optional<Integer> sumMoney = ageStream.reduce(Integer::sum);
//or Optional<Integer> sumMoney = ageStream.reduce((age1, age2)->age1+age2);
System.out.println(sumMoney);
}
7.3 收集
Collector接口中方法的实现决定了如何对流执行收集的操作(如收集到List、Set、Map)。
另外,Collectors 实用类提供了很多静态方法,可以方便地创建常见收集器实例,具体方法与实例如下表: