|
3 | 3 | import com.bobocode.util.ExerciseNotCompletedException;
|
4 | 4 |
|
5 | 5 | import java.math.BigDecimal;
|
| 6 | +import java.util.Comparator; |
6 | 7 | import java.util.Map;
|
7 | 8 | import java.util.concurrent.ThreadLocalRandom;
|
8 | 9 | import java.util.function.*;
|
@@ -249,6 +250,44 @@ public static BiFunction<Map<String, IntUnaryOperator>, String, IntUnaryOperator
|
249 | 250 | return (functionMap, functionName) -> functionMap.getOrDefault(functionName, IntUnaryOperator.identity());
|
250 | 251 | }
|
251 | 252 |
|
| 253 | + /** |
| 254 | + * Returns a comparator of type T that is comparing values extracted using the provided mapper function. |
| 255 | + * <p> |
| 256 | + * E.g. imagine you need to compare accounts by their balance values. |
| 257 | + * <pre>{@code |
| 258 | + * Comparator<Account> balanceComparator = comparing(Account::getBalance); |
| 259 | + * }</pre> |
| 260 | + * <p> |
| 261 | + * PLEASE NOTE, that @{@link Comparator} is a functional interface, and you should manually write a lambda expression |
| 262 | + * to implement it. |
| 263 | + * |
| 264 | + * @param mapper a mapper function that allows to map an object to a comparable value |
| 265 | + * @return a comparator instance |
| 266 | + */ |
| 267 | + public static <T, U extends Comparable<? super U>> Comparator<T> comparing(Function<? super T, ? extends U> mapper) { |
| 268 | + throw new ExerciseNotCompletedException(); |
| 269 | + } |
| 270 | + |
| 271 | + /** |
| 272 | + * Returns a comparator of type T that uses a provided comparator to compare objects, and only if they are equal |
| 273 | + * it's comparing values extracted using the provided mapper function. |
| 274 | + * <p> |
| 275 | + * E.g. suppose you want to compare accounts by balance, but in case two people have the same balance you want to |
| 276 | + * compare their first names: |
| 277 | + * <pre>{@code |
| 278 | + * Comparator<Account> accountComparator = thenComparing(balanceComparator, Account::getFirstName); |
| 279 | + * }</pre> |
| 280 | + * <p> |
| 281 | + * |
| 282 | + * @param comparator an initial comparator |
| 283 | + * @param mapper a mapper function that is used to extract values when initial comparator returns zero |
| 284 | + * @return a comparator instance |
| 285 | + */ |
| 286 | + public static <T, U extends Comparable<? super U>> Comparator<T> thenComparing( |
| 287 | + Comparator<? super T> comparator, Function<? super T, ? extends U> mapper) { |
| 288 | + throw new ExerciseNotCompletedException(); |
| 289 | + } |
| 290 | + |
252 | 291 | /**
|
253 | 292 | * Returns {@link Supplier} of {@link Supplier} of {@link Supplier} of {@link String} "WELL DONE!".
|
254 | 293 | *
|
|
0 commit comments