Reputation: 177
I am trying to sort a collection when I have a not equals firstValue
and secondValue
I just return a result of its comparation and It will sort it ascending way, but when these values are equals I wanna sort it by name in ascending way too. Everything works well, but when I have to sort a collection by firstValue
and secondValue
in descending way here is I bumped with a problem. When firstValue
and secondValue
are equal I wanna still sort it by name in ascending way but using the reverse order it will be sort by Name in descending way.
Here the code for ascending sorting:
prices.setPriceModels(prices.getPriceModels().stream().sorted((o1, o2) -> {
int compareResult = o1.getPrice().compareTo(o2.getPrice());
if (compareResult == 0) {
String firstCompareName = Optional.ofNullable(o1.getName()).orElse(StringUtils.EMPTY);
String secondCompareName = Optional.ofNullable(o2.getName()).orElse(StringUtils.EMPTY);
return firstCompareName.compareTo(secondCompareName);
}
return compareResult;
}).collect(Collectors.toList()));
The main goal is to sort the whole collection in a descending way and if some values are equals these values should be sort in an ascending way by name. Is it possible to achieve using reverseOrder()
of stream API? Or what is a better solution for this?
Upvotes: 0
Views: 119
Reputation: 1199
How about this comparator?
prices.getPriceModels().stream().sorted(Comparator.comparing(PriceModel::getPrice).reversed() // using PriceModel's Price to sort in descending order
// for PriceModels with equal Prices, using PriceModel' name to sort in ascending order (with null values of name's treated to be less than any non-null value)
.thenComparing(PriceModel::getName, Comparator.nullsFirst(Comparator.naturalOrder())))
.collect(Collectors.toList())
Upvotes: 1