-3

I am using java Comparator which need sorting based on below conditions -

Object1 - name subName

Object2 - name subName

Compare Object1 & Object2 based on below condition-

condition 1: if name != subName -- push it up while sorting

condition 2: if name == subName -- push it down while sorting

Can anyone help, how to implement this?

Edward N
  • 997
  • 6
  • 11
Nick M
  • 11
  • 3
  • 1
    You can probably just use that exact pseudo-code to accomplish your goal... – Mitch Connor Jul 09 '15 at 04:54
  • 1
    You should read that post : http://stackoverflow.com/questions/2784514/sort-arraylist-of-custom-objects-by-property – JDenais Jul 09 '15 at 04:55
  • http://stackoverflow.com/questions/2839137/how-to-use-comparator-in-java-to-sort http://stackoverflow.com/questions/7117044/how-to-use-java-comparator-properly – 2787184 Jul 09 '15 at 04:55

1 Answers1

-1

Comparator is a interface. So under your situation, Object1 and Object2 should be the instance from the same Object ,assume NameObject.
you can add a Comparator interface on the NameObject. and create a new "compare" method . After the you can use sort.

public class NameObject implements Comparator{
 private String name;
 private String subName;
 //getter and setter
 compare(NameObject o1, NameObject o2){
  //do some thing you want.
 }
}

That also OK if you want to implement the "Comparator" independently.

albert hou
  • 66
  • 5
  • `Comparator` is not intended for this purpose.. You should use `Comparable` instead here. – Codebender Jul 09 '15 at 05:17
  • if(sc1.getName().equalsIgnoreCase(sc1.getSubName()) && !sc2.getName().equalsIgnoreCase(sc2.getSubName())){ return 1; } if(sc2.getName().equalsIgnoreCase(sc2.getSubName()) && !sc1.getName().equalsIgnoreCase(sc1.getSubName())){ return -1; } then I have other condition which checks another field on sc1 & sc2 int diff = sc2.getTotalVal().compareTo(sc1.getTotalVal()); if(difference == 0){ return sc2.userId().compareTo(sc1.userId()); } else{ return difference; } Each time I run this code, i get different sorting results, what is wrong here? – Nick M Jul 09 '15 at 05:24
  • compareTo is Comparable interface. I think you have some confusion about how to sort the list by using Comparable or Comparator. check the link below :http://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/ – albert hou Jul 09 '15 at 06:47