Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a more concise way to write this method using Lambda Expressions?

Tags:

java

lambda

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?

like image 257
JoshuaD Avatar asked Nov 28 '18 03:11

JoshuaD


People also ask

Are there advantages of using lambda explain your answer?

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.

Which method you can pass lambda expression?

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".


Video Answer


2 Answers

I suggest you to use

    Arrays.sort(albumArray, Comparator.comparing(Album::getAlbumArtist, comparator));
like image 162
talex Avatar answered Oct 07 '22 20:10

talex


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));
like image 1
Dang Nguyen Avatar answered Oct 07 '22 20:10

Dang Nguyen