This title sounds stupid even to me, but there must be at least somewhat clever way to achieve such effect and I don't know how else to explain it. I need to sort array using sorted in stream API. Here is my stream so far:
Arrays.stream(sequence.split(" "))
.mapToInt(Integer::parseInt)
.boxed()
.sorted((a, b) -> a.compareTo(b))
.forEach(a -> System.out.print(a + " "));
Now I have two different sorts of course - ascending and descending and the sort I need to use is specified in the user input. So what I want to do is having something like switch with 2 cases: "ascending" and "descending" and a variable to store the lambda expression respectively:
switch(command) {
case "ascending": var = a.compareTo(b);
case "descending": var = b.compareTo(a);
}
Then I my sorted looks like:
.sorted((a, b) -> var)
I got the idea in a python course I attended. There it was available to store an object in variable, thus making the variable "executable". I realize that this lambda is not an object, but an expression, but I'm asking is there any clever way that can achieve such result, or should I just have
if(var)
and two diferent streams for each sort order.
The question is not stupid at all. Answering it in a broader sense: Unfortunately, there is no generic solution for that. This is due to the type inference, which determines one particular type for the lambda expression, based on the target type. (The section about type inference may be helpful here, but does not cover all details regarding lambdas).
Particularly, a lambda like
x -> y
does not have any type. So there is no way of writingGenericLambdaType
function = x -> y;
and later use
function
as a drop-in replacement for the actual lambdax -> y
.For example, when you have two functions like
you can call them both with the same lambda
but there is no way of "storing" the
x -> true
lambda in a way so that it later may be passed to both functions - you can only store it in a reference with the type that it will be needed in later:For your particular case, the answer by Konstantin Yovkov already showed the solution: You have to store it as a
Comparator<Integer>
(ignoring the fact that you wouldn't have needed a lambda here in the first place...)In Lambdas you can use a functionblock
(a,b) -> { if(anything) return 0; else return -1;}
You can switch between using
Comparator.reverseOrder()
andComparator.naturalOrder
: