按Java reverseOrder

时间:2019-06-28 19:30:54

标签: java string sorting

我有:

String[] subdivisions = {"K1","K1\\SK1","K2","K2\\SK1\\SSK1"};

我进行了排序:

Arrays.stream(subdivisions).sorted(Comparator.reverseOrder()).forEach(System.out::println);

我得到:

K2\SK1\SSK1
K2
K1\SK1
K1

但是我需要这样排序:

K2
K2\SK1\SSK1
K1
K1\SK1

如何更改排序条件? 如何正确编写排序?

2 个答案:

答案 0 :(得分:3)

这是一个自定义Comparator方法的示例,用于对所需方式进行排序:

public class Test {
    public static void main(String[] args) {
        String[] subdivisions = {"K1","K1\\SK1","K2","K2\\SK1\\SSK1"};

        Arrays.stream(subdivisions).sorted(Test::compare).forEach(System.out::println);
    }
    private static int compare(String a, String b) {
        if (a.length() < b.length() && b.startsWith(a))
            return -1; // a is prefix of b, so sort a first
        if (b.length() < a.length() && a.startsWith(b))
            return 1; // b is prefix of a, so sort b first
        return b.compareTo(a); // descending
    }
}

输出

K2
K2\SK1\SSK1
K1
K1\SK1

答案 1 :(得分:0)

...这是所需排序的lambda表达式:

Arrays.stream( subdivisions ).sorted(
    (new Comparator<String>() {
      @Override
      public int compare( String s1, String s2 ) {
        int len = Math.min( s1.length(), s2.length() );
        return( s2.substring( 0, len ).compareTo( s1.substring( 0, len ) ) );
      } }).thenComparing( String::length ) ).forEach( System.out::println );