I want to sort String elements in the array months
by length using Arrays.sort
method. I was told here, that it's possible to use lambda expressions instead of creating new class implementing Comparator. Did it exactly the same way, yet it doesn't work.
import java.util.Arrays;
import java.util.Comparator;
public class MainClass {
public static void main(String[] args)
{
String[] months = {"January","February","March","April","May","June","July","August","September","October","December"};
System.out.println(Arrays.toString(months)); //printing before
//neither this works:
Arrays.sort(months,
(a, b) -> Integer.signum(a.length() - b.length())
);
//nor this:
Arrays.sort(months,
(String a, String b) -> { return Integer.signum(a.length() - b.length()) };
);
System.out.println(Arrays.toString(months)); //printing after
}
}
You're looking for this:
The functionality you are looking for is in Java 8, which has not yet been released. It is scheduled for release in a few months if you want to wait, or if not beta downloads are available.
The cleanest way would be:
or, with a static import:
However, this would work too but is more verbose:
Or shorter:
Finally your last one:
has the
;
misplaced - it should be: