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

org.hibernate.search.util.common.impl.StreamHelper Maven / Gradle / Ivy

The newest version!
/*
 * SPDX-License-Identifier: Apache-2.0
 * Copyright Red Hat Inc. and Hibernate Authors
 */
package org.hibernate.search.util.common.impl;

import java.util.Map;
import java.util.Optional;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
import java.util.stream.Collectors;

import org.hibernate.search.util.common.AssertionFailure;

public final class StreamHelper {

	private StreamHelper() {
	}

	@SuppressWarnings("unchecked")
	public static  Collector singleElement(
			Supplier missingValueExceptionSupplier, Supplier multipleValuesExceptionSupplier) {
		return Collector.[], T>of(
				() -> new Optional[1],
				(holder, value) -> {
					if ( holder[0] != null ) {
						throw multipleValuesExceptionSupplier.get();
					}
					// Preserve null values by wrapping values in an Optional
					holder[0] = Optional.ofNullable( value );
				},
				(holder1, holder2) -> {
					if ( holder1[0] == null ) {
						return holder2;
					}
					else if ( holder2[0] != null ) {
						throw multipleValuesExceptionSupplier.get();
					}
					else {
						return holder1;
					}
				},
				holder -> {
					if ( holder[0] == null ) {
						throw missingValueExceptionSupplier.get();
					}
					// Restore null values
					return holder[0].orElse( null );
				} );
	}

	public static > Collector toMap(
			Function keyMapper, Function valueMapper,
			Supplier mapSupplier) {
		return Collectors.toMap( keyMapper, valueMapper, throwingMerger(), mapSupplier );
	}

	private static  BinaryOperator throwingMerger() {
		return (u, v) -> { throw new AssertionFailure( "Unexpected duplicate key: " + u ); };
	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy