java: Arrays.sort() with lambda expression java: Arrays.sort() with lambda expression arrays arrays

java: Arrays.sort() with lambda expression


The cleanest way would be:

Arrays.sort(months, Comparator.comparingInt(String::length));

or, with a static import:

Arrays.sort(months, comparingInt(String::length));

However, this would work too but is more verbose:

Arrays.sort(months,            (String a, String b) -> a.length() - b.length());

Or shorter:

Arrays.sort(months, (a, b) -> a.length() - b.length());

Finally your last one:

Arrays.sort(months,     (String a, String b) -> { return Integer.signum(a.length() - b.length()) }; );

has the ; misplaced - it should be:

Arrays.sort(months,     (String a, String b) -> { return Integer.signum(a.length() - b.length()); });


You're looking for this:

Arrays.sort(months, (a, b) -> Integer.signum(a.length() - b.length()));


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.