目录
一、概述
-
Java 8 API添加了一个新的抽象称为流Stream,可以让你以一种声明的方式处理数据。
-
Stream 使用一种类似用 SQL 语句从数据库查询数据的直观方式来提供一种对 Java 集合运算和表达的高阶抽象。
-
Stream API可以极大提高Java程序员的生产力,让程序员写出高效率、干净、简洁的代码。
-
这种风格将要处理的元素集合看作一种流, 流在管道中传输, 并且可以在管道的节点上进行处理, 比如筛选, 排序,聚合等。
-
元素流在管道中经过中间操作(intermediate operation)的处理,最后由最终操作(terminal operation)得到前面处理的结果。
最佳实战:以后凡是你写for循环处理数据的统一全部用StreamAPI进行替换;
Stream所有数据和操作被组合成流管道流管道组成:
-
一个数据源(可以是一个数组、集合、生成器函数、I/O管道):stream of elements
-
零或多个中间操作(将一个流变形成另一个流):filter、sorted、map
-
一个终止操作(产生最终结果):collect、sum
示例代码:
public static void testStreamApi01() {
Stream<People> peopleStream = Stream.of(new People("张三", 14),
new People("李四", 34),
new People("王五", 10),
new People("赵六", 4));
int sum = peopleStream.filter(people -> people.age > 7)
.sorted(Comparator.comparingInt(o -> o.age))
.mapToInt(people -> people.age)
.sum();
System.out.println(sum);
}
二、生成流
在 Java 8 中, 集合接口有两个方法来生成流:
-
stream() − 为集合创建串行流。
-
parallelStream() − 为集合创建并行流。
1、串行流
public static void testStreamApi02() {
List<People> list = new ArrayList<>();
list.add(new People("张三", 14));
list.add(new People("李四", 34));
list.add(new People("王五", 10));
list.add(new People("赵六", 4));
int sum = list.stream().filter(people -> {
System.out.println("filter\t" + Thread.currentThread().getName() + "\t" + people);
return people.age > 10;
})
.sorted((o1, o2) -> {
System.out.println("sorted o1:\t" + Thread.currentThread().getName() + "\t" + o1);
System.out.println("sorted o2:\t" + Thread.currentThread().getName() + "\t" + o2);
return o1.age - o2.age;
})
.mapToInt(people -> {
System.out.println("mapToInt:\t" + Thread.currentThread().getName() + "\t" + people);
return people.age;
})
.sum();
System.out.println(sum);
}
执行以上脚本,输出结果为:
filter main test.Test$People@3d494fbf
filter main test.Test$People@4783da3f
filter main test.Test$People@378fd1ac
filter main test.Test$People@49097b5d
sorted o1: main test.Test$People@4783da3f
sorted o2: main test.Test$People@3d494fbf
mapToInt: main test.Test$People@3d494fbf
mapToInt: main test.Test$People@4783da3f
48
2、并行流
public static void testStreamApi02() {
List<People> list = new ArrayList<>();
list.add(new People("张三", 14));
list.add(new People("李四", 34));
list.add(new People("王五", 10));
list.add(new People("赵六", 4));
int sum = list.stream().parallel().filter(people -> {
System.out.println("filter\t" + Thread.currentThread().getName() + "\t" + people);
return people.age > 10;
})
.sorted((o1, o2) -> {
System.out.println("sorted o1:\t" + Thread.currentThread().getName() + "\t" + o1);
System.out.println("sorted o2:\t" + Thread.currentThread().getName() + "\t" + o2);
return o1.age - o2.age;
})
.mapToInt(people -> {
System.out.println("mapToInt:\t" + Thread.currentThread().getName() + "\t" + people);
return people.age;
})
.sum();
System.out.println(sum);
}
执行以上脚本,输出结果为:
filter main test.Test$People@65b3120a
filter main test.Test$People@4d405ef7
filter main test.Test$People@6193b845
filter ForkJoinPool.commonPool-worker-1 test.Test$People@6bcbc47d
sorted o1: main test.Test$People@6bcbc47d
sorted o2: main test.Test$People@6193b845
mapToInt: ForkJoinPool.commonPool-worker-1 test.Test$People@6193b845
mapToInt: main test.Test$People@6bcbc47d
48
三、中间操作
-
filter:过滤; 挑出我们用的元素
-
map: 映射: 一一映射,a 变成 b
-
- mapToInt、mapToLong、mapToDouble
-
flatMap:打散、散列、展开、扩维:一对多映射
-
limit:获取前n条数据
-
sorted:排序
1、filter
filter 方法用于通过设置的条件过滤出元素。以下代码片段使用 filter 方法过滤出空字符串:
public static void testStreamApi04() {
List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd", "", "jkl");
// 获取空字符串的数量
long count = strings.stream().filter(String::isEmpty).count();
System.out.println(count);
}
2、map
map 方法用于映射每个元素到对应的结果,以下代码片段使用 map 输出了元素对应的平方数:
public static void testStreamApi06() {
List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
// 获取对应的平方数
List<Integer> squaresList = numbers.stream().map(i -> i * i).distinct().collect(Collectors.toList());
System.out.println(squaresList);
}
3、flatMap
使用flatMap方法的效果是,各个数组并不是分别映射成一个流,而是映射成流的内容。
public static void testStreamApi05() {
List<People> list = new ArrayList<>();
list.add(new People("张 三", 14));
list.add(new People("李 四", 34));
list.add(new People("王 五", 10));
list.add(new People("赵 六", 4));
list.stream().flatMap(people -> Arrays.stream(people.name.split(" "))).forEach(System.out::println);
}
执行以上脚本,输出结果为:
张
三
李
四
王
五
赵
六
4、limit
limit 方法用于获取指定数量的流。 以下代码片段使用 limit 方法打印出 10 条数据:
public static void testStreamApi03() {
Random random = new Random();
random.ints().limit(10).forEach(System.out::println);
}
5、sorted
sorted 方法用于对流进行排序。以下代码片段使用 sorted 方法对输出的 10 个随机数进行排序:
public static void testStreamApi07() {
Random random = new Random();
random.ints().limit(10).sorted().forEach(System.out::println);
}
6、全部的中间操作:
filter、
map、mapToInt、mapToLong、mapToDouble
flatMap、flatMapToInt、flatMapToLong、flatMapToDouble
mapMulti、mapMultiToInt、mapMultiToLong、mapMultiToDouble、
parallel、unordered、onClose、sequential
distinct、sorted、peek、limit、skip、takeWhile、dropWhile、
四、终止操作
- forEach:迭代、遍历每个数据
- collect:将流转换成集合和聚合元素
1、forEach
Stream 提供了新的方法 ‘forEach’ 来迭代流中的每个数据。以下代码片段使用 forEach 输出了10个随机数:
public static void testStreamApi03() {
Random random = new Random();
random.ints().limit(10).forEach(System.out::println);
}
2、collect
Collectors 类实现了很多归约操作,例如将流转换成集合和聚合元素。Collectors 可用于返回列表或字符串:
public static void testStreamApi08() {
List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd", "", "jkl");
List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());
System.out.println("筛选列表: " + filtered);
String mergedString = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.joining(", "));
System.out.println("合并字符串: " + mergedString);
}
3、统计
另外,一些产生统计结果的收集器也非常有用。它们主要用于int、double、long等基本类型上,它们可以用来产生类似如下的统计结果。
public static void testStreamApi09() {
List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
IntSummaryStatistics stats = numbers.stream().mapToInt(x -> x).summaryStatistics();
System.out.println("列表中最大的数 : " + stats.getMax());
System.out.println("列表中最小的数 : " + stats.getMin());
System.out.println("所有数之和 : " + stats.getSum());
System.out.println("平均数 : " + stats.getAverage());
}
4、全部的终止操作:
forEach、forEachOrdered、toArray、reduce、collect、toList、min、
max、count、anyMatch、allMatch、noneMatch、findFirst、findAny、iterator
流只有执行终止操作,前面的中间操作才会执行。如果没有终止操作,则中间操作,不会执行