Sorting in java using lambda Expression

61 Views Asked by At
class Solution {
    public int[] Sort(int[] nums) {
       int[] arr = {1, 2, 3, 4, 5};
        Arrays.sort(arr, (a, b) -> (a+""+b).compareTo((b+""+a)));//this part is showing error
        return arr;
       
    }
}

Can anyone please tell me why this code is not working?

I am trying to sort an array based on concatenated results.

1

There are 1 best solutions below

0
Kirill Vizniuk On

Not sure I understand your problem correctly, but this is one way to sort it with logic you initially showed.

public int[] Sort(int[] nums) {
    int[] arr = {1, 2, 3, 4, 5};
    return Arrays.stream(arr).boxed()
            .sorted((a, b) ->
                    (Integer.valueOf(a+""+b).compareTo(Integer.valueOf(b+""+a)))
            ).mapToInt(Integer::intValue).toArray();
}

In this case we use .boxed() to convert from int to Integer so we have .sorted() available to use. Actual concat sort algo you can adjust to your liking, and then we map to int and collect to array.