文章目录
Stream 简介
定义
Stream 是 Java8 中处理集合的关键抽象概念,它可以指定你希望对集合进行的操作,可以执行非常复杂的查找、过滤和映射数据等操作。使用 Stream API 对集合数据进行操作,就类似于使用 SQL 执行的数据库查询。也可以使用 Stream API 来并行执行操作。简而言之,Stream API提供了一种高效且易于使用的处理数据的方式。
三个步骤
创建->中间操作->中止操作
中间操作
- 筛选与切片(比如:filter-筛选,limit-切片)
- 映射(比如:map)
- 排序(比如:sorted)
中止操作
- 查找与匹配(比如:findFirst)
- 归约 (比如:reduce)
- 收集 (比如collect(Collector c))
特性
- 无存储。stream不是一种数据结构,它只是某种数据源的一个视图,数据源可以是一个数组,Java容器或I/O channel等。
- 为函数式编程而生。对stream的任何修改都不会修改背后的数据源,比如对stream执行过滤操作并不会删除被过滤的元素,而是会产生一个不包含被过滤元素的新stream。
- 惰式执行。stream上的操作并不会立即执行,只有等到用户真正需要结果的时候才会执行。
- 可消费性。stream只能被“消费”一次,一旦遍历过就会失效,就像容器的迭代器那样,想要再次遍历必须重新生成。
性能?
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-gFPQeozi-1596436433091)(http://doc.oss.yunsom.cn/storage/2020/07-30/ZHr1sJu7qnLxeLozS06iA2xs1yi6no9WgZypHXle.jpeg “size:800,1000”)]
总结如下:
- 对于简单操作,比如最简单的遍历,Stream串行API性能明显差于显示迭代,但并行的Stream API能够发挥多核特性。
- 对于复杂操作,Stream串行API性能可以和手动实现的效果匹敌,在并行执行时Stream API效果远超手动实现。
所以,如果出于性能考虑1、对于简单操作推荐使用外部迭代手动实现 2、对于复杂操作,推荐使用Stream API 3、在多核情况下,推荐使用并行Stream API来发挥多核优势, 4、单核情况下不建议使用并行Stream API。 - 如果出于代码简洁性考虑,使用Stream API能够写出更短的代码。即使是从性能方面说,尽可能的使用Stream API也另外一个优势,那就是只要Java Stream类库做了升级优化,代码不用做任何修改就能享受到升级带来的好处。<
一段代码的思考
Stream.of(1,2,3,4,5,6,7,8).sequential()
.filter(i -> {
System.out.println("过滤掉小于2的数据,数据项" + i);
return i > 2;
}).distinct()
.map(i -> {
System.out.println("给数据加五" + i);
return i + 5;
}).collect(Collectors.toList());
Stream.of(1,2,3,4,5,6,7,8).parallel()
.filter(i -> {
System.out.println("过滤掉小于2的数据,数据项" + i);
return i > 2;
}).distinct()
.map(i -> {
System.out.println("给数据加五" + i);
return i + 5;
}).collect(Collectors.toList());
Laravel collection 常用方法 -> Java
all()
all 方法返回该集合表示的底层数组
collect([1,3,5])->all();
Arrays.asList(1,3,5).stream().collect(Collectors.toList());
avg() average() max() min()
avg 方法返回给定的 平均值
collect([1,3,5])->avg();
Arrays.asList(1,3,5).stream().mapToInt(Integer::intValue).average()
contains()
contains 方法判断集合是否包含给定的项目
collect([1,3,5])->contains(1); // true
Arrays.asList(1,3,5).contains(1)
diff()
diff 方法将集合与其它集合或纯 PHP 数组进行值的比较,然后返回原集合中存在而给定集合中不存在的值
$collection = collect([1, 2, 3, 4, 5]);
$diff = $collection->diff([2, 4, 6, 8]);
$diff->all(); // [1, 3, 5]
List<Integer> collection = Arrays.asList(1, 2, 3, 4, 5);
// ArraysList 才支持 removeAll
List<Integer> diff = new ArrayList<>(collection);
diff.removeAll(Arrays.asList(2, 4, 6, 8));
filter() intersect() where() whereIn()
filter 方法使用给定的回调函数过滤集合的内容,只留下那些通过给定真实测试的内容
$collection = collect([1, 2, 3, 4]);
$filtered = $collection->filter(function ($value, $key) {
return $value > 2;
});
$filtered->all();
// [3, 4]
List<Integer> collection = Arrays.asList(1, 2, 3, 4);
List<Integer> filtered = collection.stream().filter(p -> p > 2).collect(Collectors.toList());
first()
first 方法返回集合中通过给定真实测试的第一个元素
collect([1, 2, 3, 4])->first(function ($value, $key) {
return $value > 2;
});
// 3
Optional<Integer> first = Arrays.asList(1, 2, 3, 4).stream().filter(p -> p > 2).findFirst();
if (first.isPresent()) {
System.out.println(first.get());
}
groupBy()
groupBy 方法根据给定的键对集合内的项目进行分组
$collection = collect([
['account_id' => 'account-x10', 'product' => 'Chair'],
['account_id' => 'account-x10', 'product' => 'Bookcase'],
['account_id' => 'account-x11', 'product' => 'Desk'],
]);
$grouped = $collection->groupBy('account_id');
$grouped->toArray();
/*
[
'account-x10' => [
['account_id' => 'account-x10', 'product' => 'Chair'],
['account_id' => 'account-x10', 'product' => 'Bookcase'],
],
'account-x11' => [
['account_id' => 'account-x11', 'product' => 'Desk'],
],
]
*/
@Data
@AllArgsConstructor
class Product {
private String accountId;
private String product;
}
List<Product> collection = Arrays.asList(
new Product("account-x10", "Chair"),
new Product("account-x10", "Bookcase"),
new Product("account-x11", "Desc")
);
Map<String, List<Product>> grouped = collection.stream()
.collect(Collectors.groupingBy(Product::getAccountId));
isEmpty() isNotEmpty()
如果集合是空的,isEmpty 方法返回 true,否则返回 false
collect([])->isEmpty();
// true
CollectionUtils.isEmpty(null);
keyBy()
keyBy 方法以给定的键作为集合的键。如果多个项目具有相同的键, 则只有最后一个项目回显示在新集合中
$collection = collect([
['product_id' => 'prod-100', 'name' => 'Desk'],
['product_id' => 'prod-200', 'name' => 'Chair'],
]);
$keyed = $collection->keyBy('product_id');
$keyed->all();
/*
[
'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
]
*/
@Data
@AllArgsConstructor
class Product {
private String accountId;
private String product;
}
List<Product> collection = Arrays.asList(
new Product("account-x10", "Chair"),
new Product("account-x10", "Bookcase"),
new Product("account-x11", "Desc")
);
Map<String, Product> keyed = collection.stream()
.collect(Collectors.toMap(Product::getAccountId, p->p, (exist, replace) -> (replace)));
map()
map 方法遍历集合并将每一个值传入给定的回调方法。该回调可以任意修改项目并返回,从而形成新的被修改过项目的集合:
$collection = collect([1, 2, 3, 4, 5]);
$multiplied = $collection->map(function ($item, $key) {
return $item * 2;
});
$multiplied->all();
// [2, 4, 6, 8, 10]
List<Integer> collection = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> multiplied = collection.stream().map(p -> p * 2).collect(Collectors.toList());
pluck() transform()
pluck 方法可以获取集合中给定键对应的所有值:
$collection = collect([
['product_id' => 'prod-100', 'name' => 'Desk'],
['product_id' => 'prod-200', 'name' => 'Chair'],
]);
$plucked = $collection->pluck('name');
$plucked->all();
// ['Desk', 'Chair']
@Data
@AllArgsConstructor
class Product {
private String accountId;
private String product;
}
List<Product> collection = Arrays.asList(
new Product("account-x10", "Chair"),
new Product("account-x10", "Bookcase"),
new Product("account-x11", "Desc")
);
List<String> plucked = collection.stream().map(Product::getAccountId).collect(Collectors.toList());
unique()
unique 方法返回集合中所有唯一的项目。返回的集合保留着原数组的键,所以在这个例子中,我们使用 values 方法来把键重置为连续编号的索引:
$collection = collect([1, 1, 2, 2, 3, 4, 2]);
$unique = $collection->unique();
$unique->values()->all();
// [1, 2, 3, 4]
List<Integer> unique = Arrays.asList(1, 2,2, 3, 4, 5)
.stream().distinct().collect(Collectors.toList());