0

I have:

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

I sorted:

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

I get:

K2\SK1\SSK1
K2
K1\SK1
K1

But I need to sort this way:

K2
K2\SK1\SSK1
K1
K1\SK1

How can I change sort condition? How do I write the sort correctly?

5
  • 5
    By writing your own comparator that puts "A\B" after "A"? Commented Jun 28, 2019 at 19:36
  • What if the elements are not in that order? do you expect always that result? Commented Jun 28, 2019 at 19:41
  • 2
    @YCF_L It's a sort, the original order is immaterial. reverseOrder() is not a reversing operation, it's a descending natural-order sort. Commented Jun 28, 2019 at 19:43
  • @YCF_L yes .I need to first go where the length is less than the next element. And in reverse order Commented Jun 28, 2019 at 19:45
  • @YCF_L I understood it, just cited as an example. Commented Jun 28, 2019 at 19:46

2 Answers 2

3

Here is an example of a custom Comparator method for sorting the way you want:

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

Output

K2
K2\SK1\SSK1
K1
K1\SK1
Sign up to request clarification or add additional context in comments.

Comments

0

…here is a lambda expression for the required sorting:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.