How to sort integer array in ascending and descending order using lambda only in java

  • A+
Category:Languages
int[] arr2 = new int[] {54, 432, 53, 21, 43}; 

I am using this to sort but it is giving an error.

Arrays.sort(arr2, (a, b) -> a - b); 

This is also giving an error.

arr2.sort((a, b) -> a - b); 

 


You could sort the input of type Integer[] as :

Integer[] arr2 = new Integer[] {54,432,53,21,43}; Arrays.sort(arr2, Comparator.reverseOrder()); 

or possibly with primitive types as :

int[] arr2 = new int[]{54, 432, 53, 21, 43}; int[] sortedArray = Arrays.stream(arr2)         .boxed()         .sorted(Comparator.reverseOrder()) // just use 'sorted()' for ascending order         .mapToInt(Integer::intValue)         .toArray(); 

or further using a trick from one of the existing answers (do note that it should be cautiously used with boundary values though) :

int[] sortedArray = Arrays.stream(arr2)         .map(i -> -i).sorted().map(i -> -i) // just use 'sorted()' for ascending order // Edit - use map(i -> ~i).sorted().map(i -> ~i) to be safe from the issue with Integer.MIN_VALUE         .toArray(); 

Edit: For an in-place ascending order sort, you just need to perform :

int[] arr2 = new int[]{54, 432, 53, 21, 43}; Arrays.sort(arr2); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: