Skip to content

Instantly share code, notes, and snippets.

@alexwen
Forked from JakeWharton/GuavaCollectors.java
Last active January 5, 2016 18:49
Show Gist options
  • Save alexwen/830ad1813017364087ef to your computer and use it in GitHub Desktop.
Save alexwen/830ad1813017364087ef to your computer and use it in GitHub Desktop.
/*
* 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.function.BiConsumer;
import java.util.function.Supplier;
import java.util.stream.Collector;
/** 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() {
final Supplier<ImmutableList.Builder<T>> builder = ImmutableList.Builder::new;
final BiConsumer<ImmutableList.Builder<T>, T> adder = ImmutableList.Builder::add;
return Collector.of(builder, adder, (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() {
final Supplier<ImmutableSet.Builder<T>> builder = ImmutableSet.Builder::new;
final BiConsumer<ImmutableSet.Builder<T>, T> adder = ImmutableSet.Builder::add;
return Collector.of(builder, adder, (l, r) -> l.addAll(r.build()), ImmutableSet.Builder<T>::build);
}
private GuavaCollectors() {
throw new AssertionError("No instances.");
}
}
@gjesse
Copy link

gjesse commented Jan 5, 2016

i also use this one...

    public static <T, K, V> Collector<T, com.google.common.collect.ImmutableMap.Builder<K, V>, ImmutableMap<K, V>> immutableMap(Function<T, K> keyFunc, Function<T, V> valFunc) {
        return Collector.of(com.google.common.collect.ImmutableMap.Builder::<init>, (builder, entry) -> {
            builder.put(keyFunc.apply(entry), valFunc.apply(entry));
        }, (l, r) -> {
            return l.putAll(r.build());
        }, com.google.common.collect.ImmutableMap.Builder::build, new Characteristics[0]);
    }

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