Telegram Group & Telegram Channel
Парадокс Comparator’а

Если вам нужно написать Comparator для сортировки объектов по возрастанию, обычно он выглядит так:

public class ByScoreComparator implements Comparator<User> {

@Override
public int compare(User u1, User u2) {
return (int) signum(u2.getAge() - u1.getAge());
}
}


➡️ Главная проблема — понять, от чего отнимать, чтобы порядок был правильным. Правильный ответ с первого раза получается редко, и часто мы замечаем ошибку уже после запуска кода.

Теперь это не нужно. Можно использовать ссылки на методы:

Comparator<User> comparator = Comparator
.comparingDouble(User::getAge)
.thenComparing(User::getName);
List<User> hList = ...;
hList.sort(comparator);


🗣 Такой подход упрощает создание компараторов.



tg-me.com/javarocks/265
Create:
Last Update:

Парадокс Comparator’а

Если вам нужно написать Comparator для сортировки объектов по возрастанию, обычно он выглядит так:

public class ByScoreComparator implements Comparator<User> {

@Override
public int compare(User u1, User u2) {
return (int) signum(u2.getAge() - u1.getAge());
}
}


➡️ Главная проблема — понять, от чего отнимать, чтобы порядок был правильным. Правильный ответ с первого раза получается редко, и часто мы замечаем ошибку уже после запуска кода.

Теперь это не нужно. Можно использовать ссылки на методы:

Comparator<User> comparator = Comparator
.comparingDouble(User::getAge)
.thenComparing(User::getName);
List<User> hList = ...;
hList.sort(comparator);


🗣 Такой подход упрощает создание компараторов.

BY JavaRocks


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/javarocks/265

View MORE
Open in Telegram


JavaRocks Telegram | DID YOU KNOW?

Date: |

Start with a fresh view of investing strategy. The combination of risks and fads this quarter looks to be topping. That means the future is ready to move in.Likely, there will not be a wholesale shift. Company actions will aim to benefit from economic growth, inflationary pressures and a return of market-determined interest rates. In turn, all of that should drive the stock market and investment returns higher.

The Singapore stock market has alternated between positive and negative finishes through the last five trading days since the end of the two-day winning streak in which it had added more than a dozen points or 0.4 percent. The Straits Times Index now sits just above the 3,060-point plateau and it's likely to see a narrow trading range on Monday.

JavaRocks from hk


Telegram JavaRocks
FROM USA