Sorting strings in an unusual way

This exercise intends to provide some knowledge on sorting being needed in subsequent exercises.

exercise No. 200

Implementing unusual string sorting.

Q:

Strings will often be sorted alphabetically:

ant
apple
by
eye
it
printer
van
x-ray

In this exercise we want to sort strings by length and then alphabetically:

by
it
ant
eye
van
apple
x-ray
printer

Hints:

  1. Collections.sort(List<String>, Comparator c) is your friend.

  2. Defining a Comparator class acting on strings works like:

    /**
     * Compare strings first by their length. If two strings do have
     * common length, sort them alphabetically.
     *
     */
    public class LengthCompare  implements Comparator<String> {
      @Override
      public int compare(String s1, String s2) {
        ...
       return ...;
    }
  3. Write a Junit test to assure correct sorting of strings.

A: