com.github.richardballard.arbeeutils.stream.MoreCollectors Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of arbee-utils Show documentation
Show all versions of arbee-utils Show documentation
A collection of utilities that I find useful across various projects
/*
* (C) Copyright 2016 Richard Ballard.
*
* 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.
*/
package com.github.richardballard.arbeeutils.stream;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import net.jcip.annotations.Immutable;
import org.jetbrains.annotations.NotNull;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
/**
* Some extra {@link Collector} implementations for things like guava lists.
*/
@Immutable
public enum MoreCollectors {
;
/**
* Based on code from here
*/
@NotNull
public static Collector> toImmutableList() {
final Supplier> supplier = ImmutableList.Builder::new;
final BiConsumer, T> accumulator = ImmutableList.Builder::add;
final BinaryOperator> combiner = (l, r) -> l.addAll(r.build());
final Function, ImmutableList> finisher = ImmutableList.Builder::build;
return Collector.of(supplier,
accumulator,
combiner,
finisher);
}
/**
* Based on code from here
*/
@NotNull
public static Collector> toImmutableSet() {
final Supplier> supplier = ImmutableSet.Builder::new;
final BiConsumer, T> accumulator = ImmutableSet.Builder::add;
final BinaryOperator> combiner = (l, r) -> l.addAll(r.build());
final Function, ImmutableSet> finisher = ImmutableSet.Builder::build;
return Collector.of(supplier,
accumulator,
combiner,
finisher);
}
/**
* Based on code from here
*/
@NotNull
public static Collector>
toImmutableMap(@NotNull final Function super T, ? extends K> keyMapper,
@NotNull final Function super T, ? extends V> valueMapper) {
assert keyMapper != null;
assert valueMapper != null;
final Supplier> supplier = ImmutableMap.Builder::new;
final BiConsumer, T> accumulator = (b, t) -> b.put(keyMapper.apply(t),
valueMapper.apply(t));
final BinaryOperator> combiner = (l, r) -> l.putAll(r.build());
final Function, ImmutableMap> finisher = ImmutableMap.Builder::build;
return Collector.of(supplier,
accumulator,
combiner,
finisher);
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy