|
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.function.*;
|
8 | 9 |
|
@@ -190,6 +191,44 @@ public static BiFunction<Map<String, IntUnaryOperator>, String, IntUnaryOperator
|
190 | 191 | throw new ExerciseNotCompletedException();
|
191 | 192 | }
|
192 | 193 |
|
| 194 | + /** |
| 195 | + * Returns a comparator of type T that is comparing values extracted using the provided mapper function. |
| 196 | + * <p> |
| 197 | + * E.g. imagine you need to compare accounts by their balance values. |
| 198 | + * <pre>{@code |
| 199 | + * Comparator<Account> balanceComparator = comparing(Account::getBalance); |
| 200 | + * }</pre> |
| 201 | + * <p> |
| 202 | + * PLEASE NOTE, that @{@link Comparator} is a functional interface, and you should manually write a lambda expression |
| 203 | + * to implement it. |
| 204 | + * |
| 205 | + * @param mapper a mapper function that allows to map an object to a comparable value |
| 206 | + * @return a comparator instance |
| 207 | + */ |
| 208 | + public static <T, U extends Comparable<? super U>> Comparator<T> comparing(Function<? super T, ? extends U> mapper) { |
| 209 | + throw new ExerciseNotCompletedException(); |
| 210 | + } |
| 211 | + |
| 212 | + /** |
| 213 | + * Returns a comparator of type T that uses a provided comparator to compare objects, and only if they are equal |
| 214 | + * it's comparing values extracted using the provided mapper function. |
| 215 | + * <p> |
| 216 | + * E.g. suppose you want to compare accounts by balance, but in case two people have the same balance you want to |
| 217 | + * compare their first names: |
| 218 | + * <pre>{@code |
| 219 | + * Comparator<Account> accountComparator = thenComparing(balanceComparator, Account::getFirstName); |
| 220 | + * }</pre> |
| 221 | + * <p> |
| 222 | + * |
| 223 | + * @param comparator an initial comparator |
| 224 | + * @param mapper a mapper function that is used to extract values when initial comparator returns zero |
| 225 | + * @return a comparator instance |
| 226 | + */ |
| 227 | + public static <T, U extends Comparable<? super U>> Comparator<T> thenComparing( |
| 228 | + Comparator<? super T> comparator, Function<? super T, ? extends U> mapper) { |
| 229 | + throw new ExerciseNotCompletedException(); |
| 230 | + } |
| 231 | + |
193 | 232 | /**
|
194 | 233 | * Returns {@link Supplier} of {@link Supplier} of {@link Supplier} of {@link String} "WELL DONE!".
|
195 | 234 | *
|
|
0 commit comments