Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
853 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...