|
10 | 10 | import java.nio.file.Path; |
11 | 11 | import java.util.LinkedHashMap; |
12 | 12 | import java.util.Map; |
| 13 | +import java.util.function.BiFunction; |
13 | 14 |
|
14 | 15 | /** |
15 | 16 | * Generic interface to model composable and printable metadata. |
@@ -67,6 +68,37 @@ static <T> T mergeEqual(T a, T b) { |
67 | 68 | return b; |
68 | 69 | } |
69 | 70 |
|
| 71 | + /** |
| 72 | + * Same as {@link #mergeEqual(Object, Object)} but does not crash when the two values are unequal. |
| 73 | + * Instead, both values are merged using the supplied function. |
| 74 | + * The supplied function is called only if the two given values are unequal (according to {@link Object::equals}). |
| 75 | + * |
| 76 | + * <p>The value {@code null} is treated as the neutral element in the sense that no exception is |
| 77 | + * thrown if an element is {@code null}. In this case return value is defined by {@code |
| 78 | + * mergeIfEqualElse(a, null, f) == a} and {@code mergeIfEqualElse(b, null, f) == b}. |
| 79 | + * |
| 80 | + * @param a the first element to merge |
| 81 | + * @param b the second element to merge |
| 82 | + * @param ifUnequal merge operator called when the two values are unequal |
| 83 | + * @param <T> the type of the objects to be merged |
| 84 | + * @return {@code a} if both given values are equal, otherwise the result of {@code ifUnequal.apply(a, b)} |
| 85 | + */ |
| 86 | + static <T> T mergeIfEqualElse(T a, T b, BiFunction<T, T, T> ifUnequal) { |
| 87 | + if (b == null) { |
| 88 | + return a; |
| 89 | + } |
| 90 | + |
| 91 | + if (a == null) { |
| 92 | + return b; |
| 93 | + } |
| 94 | + |
| 95 | + if (a.equals(b)) { |
| 96 | + return a; |
| 97 | + } else { |
| 98 | + return ifUnequal.apply(a, b); |
| 99 | + } |
| 100 | + } |
| 101 | + |
70 | 102 | /** |
71 | 103 | * Prints all key-value pairs to a single string. |
72 | 104 | * Falls back to {@link #show(String, Object)} on each entry. |
|
0 commit comments