Sorting Lists with a Comparator

You receive a list of names, and you’re told to sort them alphabetically.

“Well, that should be easy!” you think. You can just iterate through the list and sort it with merge sort or quick sort.

But why go through all that effort, when you can just use a Comparator?

public void sortListAlphabetically(List list){
  Collections.sort(list, new Comparator(){
    @Override
    public int compare(String a, String b){
      return a.compareTo(b);
    }
  }
}

Collections.sort takes in two parameters : a List and a Comparator.

You can override Comparator‘s compare method and specify how the sorting will work. In this case, the compareTo method compares the first string with the second, alphabetically. It does this over and over again, comparing each String to the next (using merge sort) until the whole list becomes sorted alphabetically.

Of course, since a Comparator is a functional interface, meaning it only has one method, you can call it in a more elegant way via a lambda statement.

public void sortListAlphabetically(List<String> list){
  Collections.sort(list, (a, b) -> a.compareTo(b);
}

No @Override tags. No method names. No bloated code.
Just elegance and simplicity.

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

w

Connecting to %s