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?
Using anonymous classStep - 1: Create the user-defined class. Step - 2: Create the actual class where we use the Compatator object with sort method of Collections class. Step - 3: Create the object of Compatator interface using anonymous class and implement compare method of Comparator interface.
Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.
sort() method is present in java. util. Collections class. It is used to sort the elements present in the specified list of Collection in ascending order.
Regular arguments may be passed to the method and are available within the anonymous class. This is good, it restricts the anonymous class to an few easy-to-identify variables and removes abominations of having to make some variables final.
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
}
}
);
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);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With