java - is there a faster way to extract unique values from object collection? -


i have method extract values object collection employee information:

public class employee {     public string area;     public string employee_id;     public string employee_name; } 

i'd distinct areas did thought easier, check if arraylist contains value, if not add it, takes 187ms complete, :

    long starttime = system.currenttimemillis();     arraylist<string> distinct_areas = new arraylist<string>();     (int = 0; < this.employeetress.length; i++)     {         if (!distinct_areas.contains(this.employeetress[i].area))             distinct_areas.add(this.employeetress[i].area);     }     string[] unique = new string[distinct_areas.size()];     distinct_areas.toarray(unique);     long endtime = system.currenttimemillis();     system.out.println("total execution time: " + (endtime - starttime) + "ms"); 

then thought differently see if gets faster, sorting array check last item if different add it, , little bit faster, takes 121ms complete:

    starttime = system.currenttimemillis();     string[] vs = new string[this.employeetress.length];     (int = 0; < this.employeetress.length; i++)     {         vs[i] = this.employeetress[i].area;     }     arrays.sort(vs);     arraylist<string> vsunique = new arraylist<string>();     vsunique.add(vs[0]);     (int = 0; < vs.length; i++)     {         if (!vsunique.get(vsunique.size()-1).equals(vs[i]))         {             vsunique.add(vs[i]);         }     }     string[] uni = new string[vsunique.size()];     vsunique.toarray(uni);     endtime = system.currenttimemillis();     system.out.println("total execution time: " + (endtime - starttime) + "ms"); 

i'm new java i'd know better way this. *note, code should work in android gingerbread api lvl 10 regards.

if want or count distinct areas in employee list, can use set of strings. i'm changing variable names match java standards. can count afterwards. ideally, these lazy methods.

imperative code

public set<string> areas(final list<employee> employees) {     set<string> areas = new hashset<>();     for(final employee employee: employees) {         areas.add(employee.getarea());     }     return areas; } 

functional code (google guava)

public set<string> areas(final list<employee> employees) {     return sets.newhashset(         lists.transform(employees, new function<employee, string>() {             public string apply(employee e) {                 return e.getarea();             }         })); } 

lambdas (java 8)

public set<string> areas(final list<employee> employees) {     return new hashset<string>(employees.map(e => e.getarea())); } 

Comments

Popular posts from this blog

c++ - Creating new partition disk winapi -

Android Prevent Bluetooth Pairing Dialog -

php - joomla get content in onBeforeCompileHead function -