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

jp.skypencil.guava.stream.TableCollector 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.HashBasedTable;
import com.google.common.collect.Table;

abstract class TableCollector implements Collector, E> {
    private final Function rowMapper;
    private final Function columnMapper;
    private final Function valueMapper;
    private final BinaryOperator mergeFunction;

    TableCollector(
        Function rowMapper,
        Function columnMapper,
        Function valueMapper,
        BinaryOperator mergeFunction) {
        this.rowMapper = rowMapper;
        this.columnMapper = columnMapper;
        this.valueMapper = valueMapper;
        this.mergeFunction = mergeFunction;
    }

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

    @Override
    public BiConsumer, T> accumulator() {
        return (table, data) -> {
            R row = rowMapper.apply(data);
            C column = columnMapper.apply(data);
            V value = valueMapper.apply(data);

            if (table.contains(row, column)) {
                V existing = table.get(row, column);
                table.put(row, column, mergeFunction.apply(existing, value));
            } else {
                table.put(row, column, value);
            }
        };
    }

    @Override
    public BinaryOperator> combiner() {
        return (table, another) -> {
            another.cellSet().forEach(cell -> {
                R row = cell.getRowKey();
                C column = cell.getColumnKey();
                V value = cell.getValue();

                if (table.contains(row, column)) {
                    V existing = table.get(row, column);
                    table.put(row, column, mergeFunction.apply(existing, value));
                } else {
                    table.put(row, column, value);
                }
            });
            return table;
        };
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy