Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java: Arrays.sort() with lambda expression

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
}
}
like image 544
matt-pielat Avatar asked Feb 23 '14 16:02

matt-pielat


People also ask

How do you sort a list using lambda expression?

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().

Can you use sort () on an array of strings?

To sort an array of strings in Java, we can use Arrays. sort() function.

Is there a sort method for arrays in Java?

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.


3 Answers

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()); }
);
like image 160
assylias Avatar answered Nov 08 '22 00:11

assylias


You're looking for this:

Arrays.sort(months, (a, b) -> Integer.signum(a.length() - b.length()));
like image 33
Josh M Avatar answered Nov 07 '22 23:11

Josh M


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.

like image 2
Tim B Avatar answered Nov 07 '22 22:11

Tim B