Home > Software design >  How to Sort a long[] Array in descending order in JAVA
How to Sort a long[] Array in descending order in JAVA

Time:01-28

I am trying to sort a long[] array in a way I use to sort int[] but its not working. `

long[] nums ={2,3,4,5,23,54,1};
Arrays.sort(nums,(a,b)->{
         return b-a;
         });  
System.out.println(Arrays.toString(nums));

Getting error like this :

error: no suitable method found for sort(long[],(a,b)->{ r[...] a; })

Sorry if it feel like begineer, but I am stuck.

CodePudding user response:

The Arrays class offers two methods that take an array of long primitive values as the first argument: sort and sort. Neither of those methods takes a Comparator, nor any other kind of lambda.

The error message you quote says so.

To accomplish your goal, I curiously found no convenient methods built into Java to reverse an array of long primitives. You’ll have to either swap elements in reverse order, or you’ll need to box the primitives into objects. Both approaches have been covered on Stack Overflow.

Or look to a third party library. Perhaps Google Guava (example), Eclipse Collections, or Apache Commons (example).

CodePudding user response:

Basil's answer is correct in that there is no sort method on Arrays that takes a long array and Comparator.

If you use Eclipse Collections, you can wrap the long array in a MutableLongList and use the primitive sortThis which supports a LongComparator.

@Test
public void sortLongArrayDescending()
{
    long[] nums = {2L, 3L, 4L, 5L, 23L, 54L, 1L};
    MutableLongList list = LongLists.mutable.with(nums);
    list.sortThis((a, b) -> Long.compare(b, a));
    Assertions.assertArrayEquals(new long[]{54L, 23L, 5L, 4L, 3L, 2L, 1L}, nums);
    System.out.println(Arrays.toString(nums));
}

The long array can also be sorted with a LongComparator using LongQuickSort, if you do not want to create the MutableLongList wrapper.

@Test
public void sortLongArrayDescending()
{
    long[] nums = {2L, 3L, 4L, 5L, 23L, 54L, 1L};
    LongQuickSort.sort(nums, 0, nums.length - 1, (a, b) -> Long.compare(b, a));
    Assertions.assertArrayEquals(new long[]{54L, 23L, 5L, 4L, 3L, 2L, 1L}, nums);
    System.out.println(Arrays.toString(nums));
}

There is a blog about the primitive sorting capability in the library available here.

Note: I am a committer for Eclipse Collections.

  • Related