java - Sorting ArrayList according to 2 attributes -


i want sort arraylist on base of 2 attributes. first on base of id , on base of score. each entry has score. here code.

        public class outputsentence {         int tokenid;         double similarityscore;         string title;         string quantity;         string unit;          public outputsentence(int tokenid,double similarityscore,string title,string quantity,string unit)          {             this.tokenid = tokenid;             this.similarityscore = similarityscore;             this.title = title;             this.quantity = quantity;             this.unit = unit;         }         @override         public string tostring() {             // todo auto-generated method stub             return ("token_id: "+this.tokenid + " score: "+this.similarityscore + " title: "+ this.title + " quantity: "+this.quantity+                     " unit: "+this.unit);         }          public int gettokenid()         {             return this.tokenid;         }         public double getsimilarityscore()         {             return this.similarityscore;         }      } class mycomparator implements comparator<outputsentence>{     public int compare(outputsentence s1, outputsentence s2) {         // todo auto-generated method stub         int result = integer.valueof(s1.gettokenid()).compareto(s2.gettokenid());           return result;     } }  public static void main(string[] args){          arraylist<outputsentence> finaloutput = new arraylist<outputsentence>();         finaloutput.add(new outputsentence(0, 0.1, "hello1", "half", "box"));         finaloutput.add(new outputsentence(5, 0.7, "coffee", "half", "cup"));         finaloutput.add(new outputsentence(0, 0.4, "apple juice", "glass", "one"));         collections.sort(finaloutput, new mycomparator());         for(outputsentence out:finaloutput)         system.out.println(out); } 

this giving me following results.

token_id: 0 score: 0.1 title: hello1 quantity: half unit: box
token_id: 0 score: 0.4 title: apple juice quantity: glass unit: one
token_id: 5 score: 0.7 title: coffee quantity: half unit: cup

but need these results.

token_id: 0 score: 0.4 title: apple juice quantity: glass unit: one
token_id: 0 score: 0.1 title: hello1 quantity: half unit: box
token_id: 5 score: 0.7 title: coffee quantity: half unit: cup

first sort on base of token_id , sort on base of similarity score. how can write comparator give me required results? or have write new comparator? thankful you.

as similarityscore ordered higher neccesary invert compareto result:

int result = integer.valueof(s1.gettokenid()).compareto(s2.gettokenid()); if(result == 0){ result = s2.getsimilarityscore().compareto(s1.getsimilarityscore());


Comments

Popular posts from this blog

python - pip install -U PySide error -

arrays - C++ error: a brace-enclosed initializer is not allowed here before ‘{’ token -

cytoscape.js - How to add nodes to Dagre layout with Cytoscape -