compare() example in Java

By: Emiley J Emailed: 1768 times Printed: 2516 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

The following is an example that demonstrates the power of a custom comparator. It implements the compare() method so that it operates in reverse of normal. Thus, it causes a tree set to be stored in reverse order.

// Use a custom comparator.
import java.util.*;
// A reverse comparator for strings.
class MyComp implements Comparator {
public int compare(Object a, Object b) {
String aStr, bStr;
aStr = (String) a;
bStr = (String) b;
// reverse the comparison
return bStr.compareTo(aStr);
// no need to override equals

class CompDemo {
public static void main(String args[]) {
// Create a tree set
TreeSet ts = new TreeSet(new MyComp());
// Add elements to the tree set
// Get an iterator
Iterator i = ts.iterator();
// Display elements
while(i.hasNext()) {
Object element =;
System.out.print(element + " ");

As the following output shows, the tree is now stored in reverse order:


Look closely at the MyComp class, which implements Comparatorand overrides compare( ). (As explained earlier, overriding equals( ) is neither necessary nor common.) Inside compare( ), the String method compareTo( ) compares the two strings. However, bStr-not aStr-invokes compareTo( ). This causes the outcome of the comparison to be reversed.

For a more practical example, the following program is an updated version of the TreeMap program from the previous section that stores account balances. In the previous version, the accounts were sorted by name, but the sorting began with the first name. The following program sorts the accounts by last name. To do so, it uses a comparator that compares the last name of each account. This results in the map being sorted by last name.

// Use a comparator to sort accounts by last name.
import java.util.*;
// Compare last whole words in two strings.
class TComp implements Comparator {
public int compare(Object a, Object b) {
int i, j, k;
String aStr, bStr;
aStr = (String) a;
bStr = (String) b;
// find index of beginning of last name
i = aStr.lastIndexOf(' ');
j = bStr.lastIndexOf(' ');
k = aStr.substring(i).compareTo(bStr.substring(j));
if(k==0) // last names match, check entire name
return aStr.compareTo(bStr);
return k;
// no need to override equals

class TreeMapDemo2 {
public static void main(String args[]) {
// Create a tree map
TreeMap tm = new TreeMap(new TComp());
// Put elements to the map
tm.put("John Doe", new Double(3434.34));
tm.put("Tom Smith", new Double(123.22));
tm.put("Jane Baker", new Double(1378.00));
tm.put("Todd Hall", new Double(99.22));
tm.put("Ralph Smith", new Double(-19.08));
// Get a set of the entries
Set set = tm.entrySet();
// Get an iterator
Iterator itr = set.iterator();
// Display elements
while(itr.hasNext()) {
Map.Entry me = (Map.Entry);
System.out.print(me.getKey() + ": ");
// Deposit 1000 into John Doe's account
double balance = ((Double)tm.get("John Doe")).doubleValue();
tm.put("John Doe", new Double(balance + 1000));
System.out.println("John Doe's new balance: " +
tm.get("John Doe"));

Here is the output; notice that the accounts are now sorted by last name:

Jane Baker: 1378.0
John Doe: 3434.34
Todd Hall: 99.22
Ralph Smith: -19.08
Tom Smith: 123.22
John Doe's new balance: 4434.34

The comparator class TComp compares two strings that hold first and last names. It does so by first comparing last names. To do this, it finds the index of the last space in each string and then compares the substrings of each element that begin at that point. In cases where last names are equivalent, the first names are then compared. This yields a tree map that is sorted by last name, and within last name by first name. You can see this because Ralph Smith comes before Tom Smith in the output.

Java Home | All Java Tutorials | Latest Java Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.

Bookmark and Share


1. View Comment

in statment -
new Treeset<String> (new MyComp());

why is new MyComp() written in bracket wjhat is does?

View Tutorial          By: Siddhesh Khedekar at 2009-10-27 00:14:17

Your name (required):

Your email(required, will not be shown to the public):

Your sites URL (optional):

Your comments:

More Tutorials by Emiley J
Password must include both numeric and alphabetic characters - Magento
What is Hadoop?
Returning multiple values from a web service
Tomcat and httpd configured in port 8080 and 80
Java Webservices using Netbeans and Tomcat
Java WebService connected to Database
How to Deploy a Java Web Service
Call a webservice in Java
Java WebService - Create your first web service in Java
package javax.jws does not exist
Getting Started with Android
HTML5 Location - getCurrentPosition() in HTML5
HTML5 Canvas - Using Canvas in HTML5
HTML5 - Introduction
HTML5 Video - Handling video in HTML5

More Tutorials in Java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Java File
Java String
Count number of vowels, consonants and digits in a String in Java
Reverse a number in Java
Student marks calculation program in Java
Handling Fractions in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java
Multiple Inheritance sample in Java
Java program using Method Overriding
Java program to check if user input is an even number

More Latest News
Most Viewed Articles (in Java )
InetAddress Example program in Java
Read from a COM port using Java program
Stack example in Java - push(), pop(), empty(), search()
How to use ArrayList in Java
The Basic Structure of a Simple Java program
Using StringTokenizer in Java
FileReader and FileWriter example program in Java
Transient vs Volatile modifiers in Java
Vector example in Java
Method Overriding in Java
Method Overloading (function overloading) in Java
instanceof sample program in Java
append() in Java
Student marks calculation program in Java
Reading from a file and writing to a file using Java program
Most Emailed Articles (in Java)
Text to Speech conversion program in Java
inheritance in Java
How to initialize an Array and how to copy the array
Using Charts in JasperReports
What is Unicode?
Operator Precedence in Java
Of Object, equals (), == and hashCode ()
DateFormat sample program in Java
A Simple whois program in Java
CharArrayReader example program in Java
ByteArrayOutputStream - sample program in Java
Vector example in Java
Arrays example in Java - asList(), binarySearch(), fill(), sort(), equals()
HashSet Sample program in Java
Disadvantages of using Native methods in Java