Sorting arrays using Comparator

This post explains how to sort arrays using comparator with an example.

The java jdk provides Arrays class, which has a static method named “sort”. This method takes two arguments
1) the array to be sorted
2) Comparator which contains the logic to sort the array

Below is the example which sort cards based on their rank

Main Code

1  package collections;
3  import java.util.Arrays;
4  import java.util.Comparator;
5  import java.util.HashMap;
6  import java.util.Map;
8  public class ArraysDemo {
9   public static void main(String[] args) {
10      String[] cards = {"K","J","A","Q","2","3","4"};
11      CardComparator cardComparator = new CardComparator();
12      Arrays.sort(cards, cardComparator);
13      for(int i = 0; i  rank2) {
44          return 1;
45      } else if(rank1 < rank2) {
46          return -1;
47      } else {
48          return 0;
49      }
50  }
51 }


In the above code, I have created a CardComparator class which has the logic of comparing two cards and checking which has the higher rank. Refer to line 19 to 51.

In the main method, at line 12 I am calling sort static method of Arrays class, passing the array to sort and the comparator.

The result will be a sorted array.




Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s