capci / stream
PHP 类似 Java Stream API 的库
v1.0.0
2018-10-14 01:31 UTC
Requires
- php: >=7.2.0
Requires (Dev)
- phpunit/phpunit: ~7.4
This package is auto-updated.
Last update: 2024-09-17 01:25:08 UTC
README
PHP 类似 Java Stream API 的库。
中间操作仅在终端操作被调用时才会被评估(惰性求值)。
需要 PHP 7.2 或更高版本。
使用
基本使用
Stream::of("a", "b", "c", "d", "e", "x")->filter(function ($value) { return $value !== "x"; })->map(function($value) { return strtoupper($value); })->forEach(function ($value) { echo $value . ", "; }); // A, B, C, D, E,
从值生成
- Stream。
$stream = Stream::of("a", "b", "c");
- 从数组或可遍历对象。
$stream = Stream::ofIterable([ "a", "b", "c", ]);
$stream = Stream::ofIterable(new DirectoryIterator("."));
- 从生成器函数。
$stream = Stream::ofGenerator(function () { yield "a"; yield "b"; yield "c"; });
- 以及其他
empty, concat。
中间操作
- filter
$stream = Stream::ofIterable(range(0, 10)); $stream = $stream->filter(function ($value) { return $value > 5; }); // 6 7 8 9 10
- map
$stream = Stream::ofIterable(range(0, 5)); $stream = $stream->map(function ($value) { return $value * 2; }); // 0 2 4 6 8 10
- sorted
$stream = Stream::ofIterable(range(0, 5)); $stream = $stream->sorted(function ($value1, $value2) { return $value2 - $value1; }); // 5 4 3 2 1 0
- 以及其他
flatMap, skip, skipWhile, limit, limitWhile, distinct, peek。
终端操作
- forEach
$stream = Stream::ofIterable(range(0, 5)); $stream->forEach(function ($value) { echo $value . ", "; }); // 0, 1, 2, 3, 4, 5,
- toArray
$stream = Stream::ofIterable(range(0, 5)); $array = $stream->toArray(); // [0, 1, 2, 3, 4, 5]
- reduce
$stream = Stream::ofIterable(range(0, 5)); $sum = $stream->reduce(0, function ($accum, $value) { return $accum + $value; }); // 15
- 以及其他
count, allMatch, anyMatch, nonMatch, findFirstOrDefault, findLastOrDefault, maxOrDefault, minOrDefault。
许可协议
MIT