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

io.datakernel.datastream.processor.StreamReducerSimple Maven / Gradle / Ivy

/*
 * Copyright (C) 2015-2018 SoftIndex LLC.
 *
 * 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 io.datakernel.datastream.processor;

import io.datakernel.datastream.StreamConsumer;
import io.datakernel.datastream.processor.StreamReducers.Reducer;

import java.util.Comparator;
import java.util.function.Function;

import static io.datakernel.common.Preconditions.checkNotNull;

/**
 * Perform a reduction on the elements of input streams using the  key function.
 * It is {@link AbstractStreamReducer}.
 *
 * @param  type of key for mapping
 * @param  type of input data
 * @param  type of output data
 * @param  type of accumulator
 */
public final class StreamReducerSimple extends AbstractStreamReducer {

	private final Function keyFunction;
	private final Reducer reducer;

	// region creators
	private StreamReducerSimple(Function keyFunction, Comparator keyComparator, Reducer reducer) {
		super(keyComparator);
		this.reducer = checkNotNull(reducer);
		this.keyFunction = checkNotNull(keyFunction);
	}

	/**
	 * Creates a new instance of  StreamReducerSimple
	 *
	 * @param keyComparator comparator for compare keys
	 * @param keyFunction   function for counting key
	 */
	public static  StreamReducerSimple create(Function keyFunction,
			Comparator keyComparator,
			Reducer reducer) {
		return new StreamReducerSimple<>(keyFunction, keyComparator, reducer);
	}

	@Override
	@SuppressWarnings({"unchecked", "RedundantSuppression"})
	public StreamReducerSimple withBufferSize(int bufferSize) {
		return (StreamReducerSimple) super.withBufferSize(bufferSize);
	}
	// endregion

	/**
	 * Returns  new input for this stream
	 */
	public StreamConsumer newInput() {
		return newInput(keyFunction, reducer);
	}

}