Java Collection Tutorial - Java Comparator.compare(T o1, T o2)








Syntax

Comparator.compare(T o1, T o2) has the following syntax.

int compare(T o1,  T o2)

Example

In the following code shows how to use Comparator.compare(T o1, T o2) method.

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
//from   w  w  w .j ava2s .c  o  m
class MyComparator implements Comparator<String> {
    public int compare(String a, String b) {
        return new Integer(a.length()).compareTo(b.length());
    }
}

public class Main{
    public static void main(String args[]) {
        List<String> ts = new ArrayList<String>();

        ts.add("tutorial");
        ts.add("from");
        ts.add("java2s.com");

        Collections.sort(ts);
        for (String element : ts){
          System.out.println(element + " ");
        }
        System.out.println();
        Collections.sort(ts,new MyComparator());
        for (String element : ts){
          System.out.println(element + " ");
        }

    }
}

The code above generates the following result.