12

I have class in which I am sorting a list.

import java.util.*;

public class First 
{

    private static HashMap<String,Second> msgs;

    public static void main(String[] args) 
    {           

    List<String> ls=new ArrayList<String>();


   ls.add("fourth");
   ls.add("2");
   ls.add("second");
   ls.add("first");
   ls.add("third");
   ls.add("1");

   Iterator it=ls.iterator();

   // before sorting
   while(it.hasNext())
   {
     String s=(String)it.next();
     System.out.println(s);
   }

   Collections.sort(ls, new Comparator(){
       public int compare(Object o1, Object o2) {
           return -1;
           // it can also return 0, and 1
        }
    });

System.out.println(" ");

//after sorting
   Iterator iti=ls.iterator();
   while(iti.hasNext())
   {
     String s=(String)iti.next();

     System.out.println(s);
   }

}


}

After the program is run, I get these values:

1    
third
first
second
2
fourth

My question is what is the behavior of Collection.sort() function here. On returning -1 from compare function, we get the reverse order of the list. Then how can we get other sorting orders? What is the role of returning 0, and 1?

DJClayworth
  • 26,349
  • 9
  • 53
  • 79
Osman Khalid
  • 778
  • 1
  • 7
  • 22

6 Answers6

16

Finally, I modified the sort function in this manner to get sorted data.

 Collections.sort(ls, new Comparator(){
      
      public int compare(Object o1, Object o2) 
      {
          String sa = (String)o1;
          String sb = (String)o2;
                            
          int v = sa.compareTo(sb);                             
          return v;  // it can also return 0, and 1
         
       }
 });
adhg
  • 10,437
  • 12
  • 58
  • 94
Osman Khalid
  • 778
  • 1
  • 7
  • 22
8

You can use anonymous class this way:

TreeSet<String> treeSetObj = new TreeSet<String>(new Comparator<String>() {
    public int compare(String i1,String i2)
    {
        return i2.compareTo(i1);
    }
});
Pang
  • 9,564
  • 146
  • 81
  • 122
Saurabh
  • 7,525
  • 4
  • 45
  • 46
6

Here's what the javadoc says:

int compare(T o1, T o2)

Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

Your comparator implementation doesn't respect this contract, so the result is indeterminate. It must return a negative value if it considers o1 to be less than o2. It must return a positive value if it considers o1 to be greater than o2. And it must return 0 if it considers o1 to be equal to o2. And it must of course be consistent. If o1 < o2, then o2 > o1. If o1 < o2 and o2 < o3, then o1 < o3.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
4

What is the role of returning 0, and 1?

It is to say that the o1 is equal to o2, or o1 is greater than o2.

Your anonymous comparator currently says that o1 is less than o2, for every possible value of o1 and o2. This simply makes no sense, and causes the behavior of sort to be unpredictable.

A valid comparator must implement the compare(Object, Object) method so that it behaves according to the requirements of the Comparator interface.


If your real aim is to reverse the order of the elements in a list, then don't use sort. Use Collections.reverse()

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
4

java.util.Comparator class says in compare method java doc:

a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

you can use following code:

Collections.sort(ls, new Comparator() 
{
    public int compare(Object o1, Object o2) 
    {
       if(o1 instanceof String && o2 instanceof String) 
       {
          String s_1 = (String)o1;
          String s_2 = (String)o2;

          return s_1.compareTo(s_2);
       } 
       return 0;    
    }
});

This code must work fine.You can change compare method for more flexibility.

compareTo method in String class says in its java doc:

the value 0 if the argument string is equal to this string; a value less than 0 if this string is lexicographically less than the string argument; and a value greater than 0 if this string is lexicographically greater than the string argument.

Sam
  • 6,770
  • 7
  • 50
  • 91
1

from Javadoc of Comparator

Compares its two arguments for order.  Returns a negative integer,
 zero, or a positive integer as the first argument is less than, equal
 to, or greater than the second.

So define the functionality of less than,equal or greater than for your class ,you are missing equal and greater than functionality.

Balaswamy Vaddeman
  • 8,360
  • 3
  • 30
  • 40