How to sort primitive arrays in Java

  • Post last modified:March 21, 2023
  • Reading time:3 mins read

Discussing 3 Options to sort primitive arrays in Java

Introduction

Consider we have been given int[] array, and we need to sort this array in increasing and decreasing order.

In this article, we will discuss various options to sort primitive int array.

Input Array

int[] arr = { 7,8,9,4,2,5};

Option 1

  • In this option, we will use Arrays.sort(). This method requires an Object array to be passed and we have been provided with a primitive array, hence we need to perform boxing.
  • Stream API provides boxed() to convert from primitive type to object type.
Integer[] arrBoxed = Arrays
                      .stream(arr)
                      .boxed()
                      .toArray(Integer[]::new);
Arrays.sort(arrBoxed);
System.out.println(Arrays.toString(arrBoxed));
  • If the return type requires to be int[] then we can map to primitive type using streams API.
int[] ints = Arrays.stream(arrBoxed).mapToInt(a -> a).toArray();
  • The default sorting type is ascending, but if we need descending sorting, we need to use a comparator.
Arrays.sort(arrBoxed, Comparator.reverseOrder());

Arrays.sort(arrBoxed, (a,b) -> (b-a)); // lambda

Option 2

  • In this option, we use sorted() method provided by the streams API.
int[] sortedArr = Arrays.stream(arr).sorted().toArray();
System.out.println(Arrays.toString(sortedArr));
  • The default sort type is ascending. If we need descending sort type, we need to tweak the above approach a little bit.
  • Streams API provides sorted on object type which takes comparator, so we can pass comparator to decide the order, but Streams API on primitive provides sorted() method that doesn’t takes any comparator argument, hence we cannot pass the order.
  • So we have to first box the primitive type to the Object type using boxed().
int[] reverseSortedArr = Arrays.stream(arr)
       .boxed()
       .sorted(Collections.reverseOrder())
       .mapToInt(a ->a)
       .toArray();

Option 3

  • This option is a little cumbersome since requires too many conversions and initializations.
  • We will Collections.sort() to sort the array. But Collections.sort() accepts a list as an argument, hence we first need to convert our input array to a list.
  • If we use Arrays.asList() we will get List<int[]>, because of the primitive nature of the input array ints.
List<int[]> ints1 = Arrays.asList(ints);
  • So the best way is to box the type and then convert it to a list. We are still initializing the new ArrayList with the return List from stream API.
    This is because we need the mutable list to sort the array and toList() provides the immutable list, which we cannot use for sorting.
ArrayList<Integer> integers = new ArrayList<>(Arrays
                                               .stream(arr)
                                               .boxed()
                                               .toList()
                                              );
  • Once we have an ArrayList of integers, we can now use Collections.sort() method to sort it.
ArrayList<Integer> integers = new ArrayList<>(Arrays.stream(arr).boxed().toList());
Collections.sort(integers);
// Collections.sort(integers, Comparator.reverseOrder()); sort in reverse
System.out.println(integers);

Conclusion

  • In this article, we discuss 3 options to sort Array in java. We also cover type conversion from primitive to object and how to do it using Java8 streams API.

Before You Leave

  • Let me know if I can be of any help to your career, I would love to chat or jump on a call. you can connect me over Linkedin.
  • If you like this content consider becoming medium member to support.
  • If you want to upskill your Java skills, you should definitely check out
    Java Programming Masterclass updated to Java 17
    [ 750,000 students already enrolled, with 4.5 stars]

Leave a Reply