All Downloads are FREE. Search and download functionalities are using the official Maven repository.

jp.skypencil.guava.stream.BiMapCollector Maven / Gradle / Ivy

The newest version!
package jp.skypencil.guava.stream;

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;

import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;

abstract class BiMapCollector>
        implements Collector, R> {
    private final BinaryOperator mergeFunction;
    private final Function valueMapper;
    private final Function keyMapper;

    BiMapCollector(Function keyMapper,
            Function valueMapper,
            BinaryOperator mergeFunction) {
        this.keyMapper = keyMapper;
        this.valueMapper = valueMapper;
        this.mergeFunction = mergeFunction;
    }

    @Override
    public Supplier> supplier() {
        return HashBiMap::create;
    }

    @Override
    public BiConsumer, T> accumulator() {
        return (map, data) -> {
            K key = keyMapper.apply(data);
            U value = valueMapper.apply(data);
            map.merge(key, value, mergeFunction);
        };
    }

    @Override
    public BinaryOperator> combiner() {
        return (map, another) -> {
            another.forEach((key, value) ->
                map.merge(key, value, mergeFunction)
            );
            return map;
        };
    }
}