java - How can I sort a collection of custom entities? -
i have list of custom entities need sort in order: valueone, valuetwo, , valuethree.
here code
public class apprunner { public static void main(string[] args) { detail d1 = new detail("valueone"); detail d2 = new detail("valuetwo"); detail d3 = new detail("valuefive"); detail d4 = new detail("valueten"); detail d5 = new detail("valueone"); detail d6 = new detail("valueone"); list<detail> details = new arraylist<detail>(arrays.aslist(d1, d2, d3, d4, d5, d6)); collections.sort(details); system.out.println(details); } }
my entity class
public class detail implements comparable<detail> { private string value; // there 3 options: valueone, valuetwo, , other value public detail(string value) { this.value = value; } @override public int compareto(detail detail) { string val = detail.getvalue(); if (val.equals(this.value) && val.equals("valueone")) { return 1; } else if (val.equals(this.value) && val.equals("valuetwo")) { return -1; } else { return 0; } } // getter, setters, tostring }
i think need compareto
method. in end need list in order:
- valueone
- valueone
- valueone
- valuetwo
- valuefive
use enum , compare ordinals:
enum validvalues { valueone, valuetwo, valuethree }
... , then:
public int compareto(object detail) { return integer.compare(validvalues.valueof(this.value).ordinal(), validvalues.valueof(((detail)detail).value).ordinal()); }
for larger number of values might worth collection or map, rather enum.
Comments
Post a Comment