1515 */
1616package org .springframework .data .util ;
1717
18- import lombok .experimental .UtilityClass ;
19-
2018import java .util .Arrays ;
2119import java .util .Iterator ;
2220import java .util .Optional ;
2321import java .util .function .BiConsumer ;
2422import java .util .function .BiFunction ;
23+ import java .util .function .Consumer ;
2524import java .util .function .Function ;
2625import java .util .function .Supplier ;
2726import java .util .stream .Stream ;
3433 * @author Oliver Gierke
3534 * @author Christoph Strobl
3635 */
37- @ UtilityClass
38- public class Optionals {
39-
40- private static final Object SUCCESS = new Object ();
36+ public interface Optionals {
4137
4238 /**
4339 * Returns whether any of the given {@link Optional}s is present.
@@ -165,15 +161,15 @@ public static <T, S> Optional<Pair<T, S>> withBoth(Optional<T> left, Optional<S>
165161 * @param right must not be {@literal null}.
166162 * @param consumer must not be {@literal null}.
167163 */
168- public static <T , S > Optional < Object > ifAllPresent (Optional <T > left , Optional <S > right , BiConsumer <T , S > consumer ) {
164+ public static <T , S > void ifAllPresent (Optional <T > left , Optional <S > right , BiConsumer <T , S > consumer ) {
169165
170166 Assert .notNull (left , "Optional must not be null!" );
171167 Assert .notNull (right , "Optional must not be null!" );
172168 Assert .notNull (consumer , "Consumer must not be null!" );
173169
174- return mapIfAllPresent (left , right , (l , r ) -> {
170+ mapIfAllPresent (left , right , (l , r ) -> {
175171 consumer .accept (l , r );
176- return SUCCESS ;
172+ return null ;
177173 });
178174 }
179175
@@ -195,11 +191,23 @@ public static <T, S, R> Optional<R> mapIfAllPresent(Optional<T> left, Optional<S
195191 return left .flatMap (l -> right .map (r -> function .apply (l , r )));
196192 }
197193
198- public static <T extends Throwable > void ifBothAbsent (Optional <?> left , Optional <?> right , Supplier <T > supplier )
199- throws T {
194+ /**
195+ * Invokes the given {@link Consumer} if the {@link Optional} is present or the {@link Runnable} if not.
196+ *
197+ * @param optional must not be {@literal null}.
198+ * @param consumer must not be {@literal null}.
199+ * @param runnable must not be {@literal null}.
200+ */
201+ public static <T > void ifPresentOrElse (Optional <T > optional , Consumer <? super T > consumer , Runnable runnable ) {
202+
203+ Assert .notNull (optional , "Optional must not be null!" );
204+ Assert .notNull (consumer , "Consumer must not be null!" );
205+ Assert .notNull (runnable , "Runnable must not be null!" );
200206
201- if (!left .isPresent () && !right .isPresent ()) {
202- throw supplier .get ();
207+ if (optional .isPresent ()) {
208+ optional .ifPresent (consumer );
209+ } else {
210+ runnable .run ();
203211 }
204212 }
205213}
0 commit comments