Header javaperspective.com
JavaPerspective.com  >   Advanced Tutorials  >   4. Miscellaneous Java features  >   4.2. Comparators

4.2. Comparators
Last updated: 2 January 2013.

A comparator is an object that implements the interface Comparator. You can use a comparator when you want to create an ordered collection (such as TreeSet or TreeMap) whose ordering has to be different from the natural ordering of its elements. Also, sorting methods like Collections.sort and Arrays.sort take a Comparator argument that specifies the order in which the sorting must be done.

The interface Comparator provides two methods: compare and equals. To set up a comparator, all you have to do is implement the method compare. There is no need to implement the method equals since it is already implemented in the class Object, unless you want to override it for some reason. The method compare takes two Object arguments (o1 and o2) and returns the following values:As an example, the class FileComparator shown below compares two files according to the last time they were modified: o1 is "less than" o2 if the last time o1 was modified was before the last time o2 was modified.

import java.io.File;
import java.util.Comparator;


public final class FileComparator implements Comparator<File> {

   
@Override
   
public int compare(File o1, File o2) {
         
if(o1.lastModified() < o2.lastModified())
               
return -1;

         
if(o1.lastModified() > o2.lastModified())
               
return 1;

         
return 0;
   
}

}

In the above example, @Override is an annotation which indicates that the method compare implements an interface method. The class FileComparator can be used to sort the files contained in a given directory. In the example shown below, the method sortFiles sorts the files contained in the argument directory from the oldest to the more recently modified one.

import java.io.File;
import java.util.Arrays;

public final class FilesSorter {

   
public File[] sortFiles(File directory){

         
File[] filesList = directory.listFiles();

          Arrays.sort
(filesList, new FileComparator());

         
return filesList;

   
}

}

To take another example, you can also use the class FileComparator to create a TreeSet as follows:

TreeSet<File> treeSet = new TreeSet<File>(new FileComparator());

As a result, the TreeSet object will be ordered according to the order specified in the class FileComparator.


You are here :  JavaPerspective.com  >   Advanced Tutorials  >   4. Miscellaneous Java features  >   4.2. Comparators
Next tutorial :  JavaPerspective.com  >   Advanced Tutorials  >   4. Miscellaneous Java features  >   4.3. Singletons

Copyright © 2013 - 2016. JavaPerspective.com. All rights reserved.  ( Terms | Contact | About ) 
Java is a trademark of Oracle Corporation
Image 1 Image 2 Image 3 Image 4 Image 5 Image 6 Image 7