java - Group objects in list by multiple fields -


i have simple object this

public class person{   private int id;  private int age;  private string hobby;   //getters, setters  } 

i want group list of person attributes

output should this

person count/age/hobby 2/18/basket 5/20/football 

with chart more understanding

chart

x axis : hobby repartition y axis : count of person distribution

colors represents age

i managed group 1 attribute using map, can't figure how group multiples attributes

//group age . want group hobby  personmapgroupped = new linkedhashmap<string, list<person>>();  (person person : listperson) {             string key = person.getage();             if (personmapgroupped.get(key) == null) {                 personmapgroupped.put(key, new arraylist<person>());             }             personmapgroupped.get(key).add(person);         } 

then retrieve groupable object this

  (map.entry<string, list<person>> entry : personmapgroupped .entryset()) {              string key = entry.getkey();// group age             string value = entry.getvalue(); // person count             // want retieve group hobby here too...          } 

any advice appreciated. thank much

implement methods comparing people according different fields. instance, if want group age, add method person:

public static comparator<person> getagecomparator(){     return new comparator<person>() {          @override         public int compare(person o1, person o2) {             return o1.age-o2.age;         }     }; } 

then can call: arrays.sort(people,person.getagecomparator()) or use following code sort collection:

list<person> people = new arraylist<>(); people.sort(person.getagecomparator()); 

to sort using more 1 comparator simultaneously, first define comparator each field (e.g. 1 age , 1 names). can combine them using comparatorchain. use comparatorchain follows:

comparatorchain chain = new comparatorchain(); chain.addcomparator(person.getnamecomparator()); chain.addcomparator(person.getagecomparator()); 

Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -