-4

Generally I saw- To implement comparator in java collections we need 2 classes , one class call the sort function and 2nd class implement comparator.. I want to know Is there any way to implement whole comparator concept in a single class??

shmosel
  • 49,289
  • 6
  • 73
  • 138
  • Yes it is....... – Jens Mar 30 '17 at 14:42
  • why can't you simply try and see ?? – Ravi Mar 30 '17 at 14:42
  • Please give me an example If possible.. – Mohit Gandhi Mar 30 '17 at 14:43
  • Why do you want to create in one class?...Whats wrong with two classes – Arvindsinc2 Mar 30 '17 at 14:43
  • You *always* implement `Comparator` in a single class. Then, yes, you need other classes to *use* it -- either your own, or any of the many in the JDK that do. Perhaps if you showed us an example of what the two things are you think you need to implement, and told us why you can't get rid of the one that doesn't contain `implements Comparator`, we could help better. – T.J. Crowder Mar 30 '17 at 14:45
  • public class C implements Comparator { int rollno; String name; int age; C(int rollno,String name,int age) { this.rollno=rollno; this.name=name; this.age=age; } public static void main(String args[]) { ArrayList al=new ArrayList(); C obj1=new C(101,"Vijay",23); C obj2=new C(106,"Ajay",27); al.add(obj1); al.add(obj2); Collections.sort(al,Comparator); public int compare(C o1,C o2) { return o1.name.compareTo(o2.name); } } } – Mohit Gandhi Mar 30 '17 at 14:47
  • In this example , I want to implement Comparator and compare function and result in single class without using any other user defined class. But It give me some error on calling sort function – Mohit Gandhi Mar 30 '17 at 14:48
  • @MohitGandhi Please don't change your question, especially once it's been answered acceptably. The answer to your edited question can be found [here](http://stackoverflow.com/questions/4108604/java-comparable-vs-comparator). If you have something else to ask, post it separately. – shmosel May 02 '17 at 07:54

1 Answers1

1

Yes, you can use comparator without creating that second class. if you want to use comparator in one class, you have 3 options. You can 1. create an inner class. 2. create an anonymous class, and 3. (Which is the best way to do it) use a lambda. Using lambdas are the best way to create readable code.

So in your code, this should work:

al.sort((o1, o2) -> o1.name.compareTo(o2.name));

It's that easy. This is new in Java 8, and I'm very glad they added this. Your question touches on one of the downfalls of OOP. Sometimes, you don't WANT to pass objects, only behavior, which is what lambdas accomplish.

Nick Ziebert
  • 1,258
  • 1
  • 9
  • 17