compare() example in Java
By: Emiley J in Java Tutorials on 2007-09-14
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.
import java.util.*; // A reverse comparator for strings. class MyComp implements Comparator{ public int compare(String a, String b) { // reverse the comparison return b.compareTo(a); } } class CompDemo { public static void main(String args[]) { // Create a tree set with custom comparator TreeSet ts = new TreeSet (new MyComp()); // Add elements to the tree set ts.add("C"); ts.add("A"); ts.add("B"); ts.add("E"); ts.add("F"); ts.add("D"); // Get an iterator Iterator i = ts.iterator(); // Display elements while(i.hasNext()) { String element = i.next(); System.out.print(element + " "); } System.out.println(); } }
As the following output shows, the tree is now stored in reverse order:
F E D C B A
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.
import java.util.*; // Compare last whole words in two strings. class TComp implements Comparator{ public int compare(String aStr, String bStr) { int i, j, k; // 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); else return k; } } 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", 3434.34); tm.put("Tom Smith", 123.22); tm.put("Jane Baker", 1378.00); tm.put("Todd Hall", 99.22); tm.put("Ralph Smith", -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 = itr.next(); System.out.print(me.getKey() + ": "); System.out.println(me.getValue()); } System.out.println(); // Deposit 1000 into John Doe's account double balance = tm.get("John Doe"); tm.put("John Doe", 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.
Add Comment
This policy contains information about your privacy. By posting, you are declaring that you understand this policy:
- Your name, rating, website address, town, country, state and comment will be publicly displayed if entered.
- Aside from the data entered into these form fields, other stored data about your comment will include:
- Your IP address (not displayed)
- The time/date of your submission (displayed)
- Your email address will not be shared. It is collected for only two reasons:
- Administrative purposes, should a need to contact you arise.
- To inform you of new comments, should you subscribe to receive notifications.
- A cookie may be set on your computer. This is used to remember your inputs. It will expire by itself.
This policy is subject to change at any time and without notice.
These terms and conditions contain rules about posting comments. By submitting a comment, you are declaring that you agree with these rules:
- Although the administrator will attempt to moderate comments, it is impossible for every comment to have been moderated at any given time.
- You acknowledge that all comments express the views and opinions of the original author and not those of the administrator.
- You agree not to post any material which is knowingly false, obscene, hateful, threatening, harassing or invasive of a person's privacy.
- The administrator has the right to edit, move or remove any comment for any reason and without notice.
Failure to comply with these rules may result in being banned from submitting further comments.
These terms and conditions are subject to change at any time and without notice.
- Data Science
- Android
- React Native
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Related Tutorials
Read a file having a list of telnet commands and execute them one by one using Java
Open a .docx file and show content in a TextArea using Java
Step by Step guide to setup freetts for Java
Of Object, equals (), == and hashCode ()
Using the AWS SDK for Java in Eclipse
DateFormat sample program in Java
concurrent.Flow instead of Observable class in Java
Calculator application in Java
Sending Email from Java application (using gmail)
Comments