You might want to use this Comparator<Order> adjusted by the o.side parameter.
static Comparator<Order> buyComparator() {
return (l, r) -> {
Comparator<Order> comparator = Comparator.comparing(Order::getPrice);
comparator = "BUY".equals(l.side) && "BUY".equals(r.side) ?
comparator : comparator.reversed();
return comparator.compare(l ,r);
};
}
Then the usage is fairly simple, you can return a new sorted list through the Stream API or mutate the original one:
- Stream API:
List<Order> sortedOrders = orders.stream()
.sorted(buyComparator())
.collect(Collectors.toList());
- Mutate the original one using
Collections.sort(List, Comparator):
Collections.sort(orders, buyComparator());
By the way, there are two mistakes in your code:
- There is no
Stream::sort method but Stream::sorted.
- The Stream itself is not terminated so the pipelines never execute. Such terminal operations are
collect, reduce, findFirst etc...
...why it doesn't complain if I use only sorted(comparing(Order::getPrice)) instead of ternary operation?
Because the sorted method expects Comparator<Order> but your lambda expression is not compliant with that.
Firstly, your lambda expression starts with o -> ... which is not correct as long as the method in Comparator is int compare(T o1, T o2) hence the lambda expression should look like (o1, o2).
Secondly, the return type must be int (because of int compare(T o1, T o2)). Using only comparing(Order::getPrice) is okey but as long as you choose lambda expression over a method reference, then the return type is clearly seen:
// this is your lambda expression
BiFunction<Order, Order, Comparator<Order>> biFunction = (l, r) ->
"BUY".equals(l.side) && "BUY".equals(r.side) ?
Comparator.comparing(Order::getPrice) :
Comparator.comparing(Order::getPrice).reversed();
List<Order> sortedOrders = orders.stream()
.sorted((l, r) -> biFunction.apply(l, r).compare(l ,r))
.collect(Collectors.toList());
This is obviously not Comparator<Order>, but can be used. The whole thing can be simplified to the solution I have descibed above.