java - Trying to sort a map where the value is an object and I can sort by multiple values in the object -
java - Trying to sort a map where the value is an object and I can sort by multiple values in the object -
i'm trying sort map based on different possible values in pupil object. doesn't seem working me , can't seem figure out why. help appreciated. thanks!
protected static map<integer, student> sort(map<integer, student> unsortermap, string field) { comparator<integer> valuecomparator = new comparator<integer>() { public int compare(integer k1, integer k2) { int compare; if(field.equalsignorecase("name")) { compare = unsortermap.get(k1).getname().compareto(unsortermap.get(k2).getname()); } else { compare = integer.compare(unsortermap.get(k1).getindex(), unsortermap.get(k2).getindex()); } if (compare == 0) homecoming 1; else homecoming compare; } }; map<integer, student> sortedmap = new treemap <integer, student>(valuecomparator); sortedmap.putall(unsortermap); homecoming sortedmap; }
your comparator violates comparator
contract. javadoc:
the implementor must ensure sgn(compare(x, y)) == -sgn(compare(y, x)) x , y
but in code, have
if (compare == 0) homecoming 1; else homecoming compare;
if 2 students have same value field utilize comparison, both compare(x,y)
, compare(y,x)
homecoming 1.
java sorting dictionary
Comments
Post a Comment