Skip to content

Instantly share code, notes, and snippets.

@JakeWharton
Last active May 10, 2018 09:08
Show Gist options
  • Save JakeWharton/9734167 to your computer and use it in GitHub Desktop.
Save JakeWharton/9734167 to your computer and use it in GitHub Desktop.
Example Java 8 collectors for Guava.
/*
* Copyright (C) 2014 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import java.util.stream.Collector;
import static java.util.stream.Collector.Characteristics.UNORDERED;
/** Stream {@link Collector collectors} for Guava types. */
public final class GuavaCollectors {
/** Collect a stream of elements into an {@link ImmutableList}. */
public static <T> Collector<T, ImmutableList.Builder<T>, ImmutableList<T>> immutableList() {
return Collector.of(ImmutableList.Builder::new, ImmutableList.Builder::add,
(l, r) -> l.addAll(r.build()), ImmutableList.Builder<T>::build);
}
/** Collect a stream of elements into an {@link ImmutableSet}. */
public static <T> Collector<T, ImmutableSet.Builder<T>, ImmutableSet<T>> immutableSet() {
return Collector.of(ImmutableSet.Builder::new, ImmutableSet.Builder::add,
(l, r) -> l.addAll(r.build()), ImmutableSet.Builder<T>::build, UNORDERED);
}
private GuavaCollectors() {
throw new AssertionError("No instances.");
}
}
@david-bakin
Copy link

Just to provide another variation, here's the collector for map:

/** Collect a stream of elements into an {@link ImmutableMap}. */
public static <T, K, V> Collector<T, ImmutableMap.Builder<K, V>, ImmutableMap<K, V>>
        toImmutableMap(Function<? super T, ? extends K> keyMapper,
                       Function<? super T, ? extends V> valueMapper) {
    return Collector.of(ImmutableMap.Builder<K, V>::new,
        (r, t) -> r.put(keyMapper.apply(t), valueMapper.apply(t)),
        (l, r) -> l.putAll(r.build()),
        ImmutableMap.Builder<K, V>::build,
        Collector.Characteristics.UNORDERED);
}

@x3ro
Copy link

x3ro commented Mar 3, 2017

Guava 21.0 has these built-in. See e.g. com.google.common.collect.ImmutableSet.toImmutableSet.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment