Guavate: tiny library bridging Guava and Java8

Datetime:2016-08-23 00:37:04          Topic: Java8           Share

Java8 is great and adds some useful abstractions to the JDK that have found popularity in the Java community via the wonderful Guava commons library from Google. Group discussion indicates that there will be a Guava version soon that requires Java 8 and closes the gap between Guava and Java8. However, until such a time, the rest of us using Guava+Java8 need a tiny shim library for things like Collector implementation’s that produce Guava Immutable collections.

As always Stephen Colebourne threw together exactly such a tiny utility class: Guavate . Unfortunately, it’s buried inside of Strata, and for all of my projects I don’t want to depend on Strata just for this tiny shim. Also, I have a few Java8 shim methods myself that could use a home. Therefore, I forked Colebourne’s Guavate and have released it to Maven Central for anyone else that wants to add this tiny shim library to their Java8 projects:

<dependency>
    <groupId>com.github.steveash.guavate</groupId>
    <artifactId>guavate</artifactId>
    <version>1.0.0</version>
</dependency>

There are Collector implementations for each of the Immutable collections:

List<String> inputs = Lists.newArrayList("a", "b", "c");
ImmutableSet<String> outputs = inputs.stream()
    .map(String::toUpperCase)
    .filter(it -> !it.startsWith("b"))
    .collect(Guavate.toImmutableSet());
// outputs is an immutable set of "a" and "c"

There are also some convenient methods for collecting to maps from Map.Entry (and Common-Lang3’s Pair as it implements Entry):

Map<String, Integer> inputs = ImmutableMap.of(
    "bob", 1, 
    "jon", 2, 
    "mary", 3
);
Map<String,Integer> outputs = inputs.entrySet().stream()
    .map(e -> Pair.of(e.getKey().toUpperCase(), e.getValue()))
    .collect(Guavate.entriesToMap());
// outputs is a map of BOB:1, JON:2, MARY:3

Converting an arbitrary iterable into a stream (which should’ve been in the JDK to begin with):

Iterable<String> values = // ...
Stream<String> streamVals = Guavate.stream(values);

and converting an Optional into a stream of zero or one element:

Optional<String> maybe = // ...
Stream<String> stream = Guavate.stream(maybe);

Checkout the GitHub project page to follow for updates or submit pull requests with your own Java8 additions:





About List