Java Comparator

Good day. It seems that temperatures in the Twin Cities will go up as high as 68 F tomorrow and then for the following 5 to 7 days the temperature will be with highs in the 30s and 40s. Most of the snow has melted. Hopefully the snow will be gone in the next week or two.

I took a look at the HackerRank challenge Java Comparator. You are required to generate a comparator to sort an array of objects type Player. Each player has a name and a score. The sort has to be in descending order. If two players have the same score then the names should be sorted in ascending order.

The scaffolding to test the code is provided. I generated a Solution in Java 8 using the Eclipse IDE.

The problem has a single test case. The output from the console follows:

5
amy 100
david 100
heraldo 50
aakansha 75
aleksa 150

aleksa 150
amy 100
david 100
aakansha 75
heraldo 50

As you can see the results are ordered in descending score and Amy and David with equal scores of 100 are ordered by name in ascending order.

The code for the Checker class which implements the comparator follows:

/*
 * Comparator that sorts them in order of decreasing score.
 * If 2 or more players have the same score, 
 * sort those players alphabetically by name. 
 */
class Checker implements Comparator<Player> {
	
	public int compare(Player p1, Player p2) {
		
		// **** sort by score ****
		if (p1.score > p2.score)
			return -1;
		if (p1.score == p2.score) {
			
			// **** sort by name ****
			return p1.name.compareTo(p2.name);
		}
		return 1;
	}
}

The code compares the players by score and when there is a tie, it uses their names.

The entire solution is in my GitHub repository.

If you have comments regarding this or any other post in this blog, or if you need help on any aspect of a software development project, please leave me a note below. Requests for project assistance will not be made public.

John

Follow me on Twitter:  @john_canessa

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.