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
}
}
In this article, Lambda Expression with Collections is discussed with examples of sorting different collections like ArrayList, TreeSet, TreeMap, etc. Sorting Collections with Comparator (or without Lambda): We can use Comparator interface to sort, It only contains one abstract method: – compare().
To sort an array of strings in Java, we can use Arrays. sort() function.
Using the Arrays class in Java, you have access to various methods you can use to manipulate arrays. One of the methods we'll be using from the Arrays class is the sort() method which sorts an array in ascending order.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With