Mohammad Basheer
Mohammad Basheer

Reputation: 1

Sorting in java using lambda Expression

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.

Upvotes: -1

Views: 85

Answers (1)

Kirill Vizniuk
Kirill Vizniuk

Reputation: 144

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.

Upvotes: -1

Related Questions