java - Sorting objects by fields subsequently -
the issue sort huge collection of pojo objects
class entity{ string key1; string key2; string key3; string key4; }
in alphabetical order of fields subsequently. means first sorting key1, key2 , etc. of key can null. question simplest way that.
a way append keys together
, use comparator<entity>
-
// keys of entity appended , compared other entity int compare(entity e1, entity e2){ return appendandhandlenull(e1.key1, e1.key2, e1.key3).compareto(appendandhandlenull(e2.key1, e2.key2, e2.key3)); } /** * method keys of entity in appended form */ private static final string appendandhandlenull(string list...){ stringbuilder result = new stringbuilder (); for(string s : list){ result.append(s!=null?s:"").append(" ");//note: space appended after each key } return result.tostring(); }
what doing here is..... keys of entity appended in order in comparison need done, , compared other entity.
you might need trim each value before appending.
edited: necessary seperate each key space
code work properly.
code fixed above. @thilo pointing it.
Comments
Post a Comment