Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jun 26th, 2012  |  syntax: None  |  size: 0.89 KB  |  hits: 13  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Group by field name in java
  2. public class Person{
  3.     String name;
  4.     String surname;
  5.     ....
  6. }
  7.        
  8. List<Person> allPeople; // your list of all people
  9. Map<String, List<Person>> map = new HashMap<String, List<Person>>();
  10. for (Person person : allPeople) {
  11.    String key = person.getName();
  12.    if (map.get(key) == null) {
  13.       map.put(key, new ArrayList<Person>());
  14.    }
  15.    map.get(key).add(person);
  16. }
  17.  
  18. List<Person> davids = map.get("David");
  19.        
  20. void addPerson(Person p, Map<String, List<Person>> map){
  21.   ArrayList<Person> lst = map.get(p.name);
  22.   if(lst == null){
  23.      lst = new ArrayList<Person>();
  24.   }
  25.   lst.add(p);
  26.   map.put(p.name, lst);
  27. }
  28. ...
  29. for(Person p:personsCollection>){
  30.    addPerson(p, map);
  31. }
  32.        
  33. class Person (val name: String, val surname: String ="Smith")
  34. val li = List (new Person ("David"), new Person ("Joe"), new Person ("Sue"), new Person ("David", "Miller"))
  35. li.groupBy (_.name)