Utilities for working with Java 8 streams
Java
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
gradle
src
.gitignore
LICENSE
README.md
build.gradle
circle.yml
gradlew
gradlew.bat

README.md

streams

Utilities for working with Java 8 streams. MoreStreams provides a few convenient static methods; KeyedStream makes working with streams of Map entries readable. MoreCollectors provides collectors for immutable collections.

CircleCI Build Status Download

MoreCollectors

import com.palantir.common.streams.MoreCollectors;

MoreCollectors allows one to convert their stream directly into a collection that is immutable, the underlying collection type is not guaranteed.

Stream.of(1, 2, 3)
    .map(v -> v * 2)
    .collect(MoreCollectors.toImmutableList());

The collectors currently provided:

  • toImmutableList()
  • toImmutableSet()
  • toImmutableMap()

KeyedStream

Consider using streamex's EntryStream instead of this class.

import com.palantir.common.streams.KeyedStream;

A KeyedStream<K, V> is syntactic sugar around a Stream<Map.Entry<K, V>>, with methods for filtering/updating keys, values and whole entries. You can create a KeyedStream from a Map, or from a Stream or Iterable, giving initially identical keys and values.

KeyedStream.of(Stream.of(1, 2, 3))  // keys and values are initially identical
    .map(v -> v * 2)                // keys remain unchanged, values are doubled
    .mapKeys(Integer::toString)     // values remain unchanged
    .collectToMap();                // returns a Map<String, Integer>

Each map function also accepts a BiFunction, making it easy to modify keys based on values, and vice versa:

KeyedStream.stream(map)
    .map((k, v) -> new FooType(k, v))  // keys remain unchanged
    .collectToMap();

MoreStreams

import static com.palantir.common.streams.MoreStreams.*;

MoreStreams::stream creates streams from:

  • Iterables (equivalent to the wordy StreamSupport.stream(iterable.spliterator(), false))
  • Optionals (equivalent to optionalValue.map(Stream::of).orElse(Stream.of()))
  • Iterators (equivalent to StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false);)