Minor optimization based on Collections.sort was added.