2

I am trying to sort a character array with a custom sort order in Java using a lambda function as comparator -

order = "edcba"
char[] arr = {'a','b','c','d','e'}

I am trying this code :

Arrays.sort(arr, (a,b)->Integer.compare(order.indexOf(a), order.indexOf(b)));

However, this gives me the following error -

Line 4: error: no suitable method found for sort(char[],(a,b)->Int[...]f(b)))
        Arrays.sort(arr, (a,b)->Integer.compare(order.indexOf(a), order.indexOf(b)));
              ^
    method Arrays.<T#1>sort(T#1[],Comparator<? super T#1>) is not applicable
      (inference variable T#1 has incompatible bounds
        equality constraints: char
        lower bounds: Object)
    method Arrays.<T#2>sort(T#2[],int,int,Comparator<? super T#2>) is not applicable
      (cannot infer type-variable(s) T#2
        (actual and formal argument lists differ in length))   where T#1,T#2 are type-variables:
    T#1 extends Object declared in method <T#1>sort(T#1[],Comparator<? super T#1>)
    T#2 extends Object declared in method <T#2>sort(T#2[],int,int,Comparator<? super T#2>)

I have tried using similar code before for integer arrays to success. Can someone explain where I am going wrong here?

Avishek De
  • 25
  • 3
  • It's a problem with boxing: [`Arrays.sort`](https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/util/Arrays.html#sort(T%5B%5D,java.util.Comparator)) requires a `Comparator super T> c`, but your lambda is deduced to accept primitive `char`s, and those are not `Object`s. – Hulk Jul 14 '21 at 09:04
  • 1
    The problem is that there is no `Arrays.sort(char[], Comparator)` method. `sort(T[], Comparator super T>)` is not applicable here as `T` cannot be `char` and auto-boxing doesn't work here. You'd need to convert to `Character[]` here. – Thomas Jul 14 '21 at 09:07

1 Answers1

2

You can try this code.

String order = "edcba";
char[] arr = {'a', 'b', 'c', 'd', 'e'};

var characters = new String(arr).chars()
        .mapToObj(c -> (char) c)
        .toArray(Character[]::new);

Arrays.sort(characters, 0, arr.length, Comparator.comparingInt(order::indexOf));

for (char ch : characters) {
    System.out.print(ch);
}

Explanation. Here is documentation for sort method https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html#sort(T[],int,int,java.util.Comparator)

The first issue, you are missing the range (start and end).

And the second issue, the method accepts generic type T. So, you cannot pass a primitive array to the method (char[]). Because of that, the first step is to covert char[] to Character[], and then use the sort() method.

djm.im
  • 3,295
  • 4
  • 30
  • 45