Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
847 views
in Technique[技术] by (71.8m points)

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
}
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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()); }
);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...