capci/stream

Java-like Stream API library for PHP

v1.0.0 2018-10-14 01:31 UTC

This package is auto-updated.

Last update: 2024-04-17 00:31:33 UTC


README

Build Status

Java-like Stream API library for PHP.

Intermediate operations are not evaluated until terminal operation is invoked (lazy evaluation).

Requires PHP 7.2 or newer.

Usage

Basic usage.

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,

Generate Stream

  • from values.
$stream = Stream::of("a", "b", "c");
  • from array or Traversable.
$stream = Stream::ofIterable([
    "a",
    "b",
    "c",
]);
$stream = Stream::ofIterable(new DirectoryIterator("."));
  • from generator function.
$stream = Stream::ofGenerator(function () {
    yield "a";
    yield "b";
    yield "c";
});
  • and others

empty, concat.

Intermediate operation

  • 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
  • and others

flatMap, skip, skipWhile, limit, limitWhile, distinct, peek.

Terminal operation

  • 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
  • and others

count, allMatch, anyMatch, nonMatch, findFirstOrDefault, findLastOrDefault, maxOrDefault, minOrDefault.

License

MIT