I'm sorting an array of "Albums" by the output of their method getAlbumArtist()
, using a custom comparator class, AlphaNumComparator, which has a method compare
, which compares two strings.
I have the following code, which works:
AlphanumComparator comparator = new AlphanumComparator ( CaseHandling.CASE_INSENSITIVE );
Arrays.sort( albumArray, ( Album a, Album b ) -> {
return comparator.compare( a.getAlbumArtist(), b.getAlbumArtist() );
});
This seems like the sort of code that could be simplified/made more clear with some of the new langauge features in Java, but I can't quite make the pieces fit. Is it possible, or is it about as consice as it gets?
Advantages of Lambda ExpressionFewer Lines of Code − One of the most benefits of a lambda expression is to reduce the amount of code. We know that lambda expressions can be used only with a functional interface. For instance, Runnable is a functional interface, so we can easily apply lambda expressions.
If we need to pass a lambda expression as an argument, the type of parameter receiving the lambda expression argument must be of a functional interface type. In the below example, the lambda expression can be passed in a method which argument's type is "TestInterface".
I suggest you to use
Arrays.sort(albumArray, Comparator.comparing(Album::getAlbumArtist, comparator));
Assume the albumArray
is a list
, you can do this
albumArray.sort(Comparator.comparing(Album::getAlbumArtist, String.CASE_INSENSITIVE_ORDER));
else you can do this
Arrays.sort(albumArray, Comparator.comparing(Album::getAlbumArtist, String.CASE_INSENSITIVE_ORDER));
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