
org.hibernate.search.util.common.impl.StreamHelper Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of hibernate-search-util-common Show documentation
Show all versions of hibernate-search-util-common Show documentation
Hibernate Search common utilities
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 super T, ? extends K> keyMapper, Function super T, ? extends U> 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