java: Arrays.sort() with lambda expression

2022-09-01 09:17:23

我想使用方法按长度对数组中的字符串元素进行排序。我在这里被告知,可以使用lambda表达式,而不是创建新的类来实现比较器。它以完全相同的方式做了,但它不起作用。monthsArrays.sort

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
}
}

答案 1

最干净的方法是:

Arrays.sort(months, Comparator.comparingInt(String::length));

或者,使用静态导入:

Arrays.sort(months, comparingInt(String::length));

但是,这也行得通,但更详细:

Arrays.sort(months,
            (String a, String b) -> a.length() - b.length());

或更短:

Arrays.sort(months, (a, b) -> a.length() - b.length());

最后是你的最后一个:

Arrays.sort(months, 
    (String a, String b) -> { return Integer.signum(a.length() - b.length()) }; 
);

有错位 - 它应该是:;

Arrays.sort(months, 
    (String a, String b) -> { return Integer.signum(a.length() - b.length()); }
);

答案 2

你正在寻找这个:

Arrays.sort(months, (a, b) -> Integer.signum(a.length() - b.length()));