Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
477 views
in Technique[技术] by (71.8m points)

dictionary - Group by field name in Java

I'm trying to group Java objects by their field, i.e Person.java

public class Person {
    String name;
    String surname;
    ....
}

So if I have n Person objects, what would be the easiest way to get all people name "David" into a map like Map<String, List<Person>> map;?

I found this on Google (but it doesn't compile), it seems to be the thing I'm looking for: http://www.anzaan.com/2010/06/grouping-objects-using-objects-property/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There's probably a library that can do this more simply, but it's not too hard to do it manually:

List<Person> allPeople; // your list of all people
Map<String, List<Person>> map = new HashMap<String, List<Person>>();
for (Person person : allPeople) {
   String key = person.getName();
   if (map.get(key) == null) {
      map.put(key, new ArrayList<Person>());
   }
   map.get(key).add(person);
}

List<Person> davids = map.get("David");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...