在Java中按字段名称分组
我正在尝试按其字段对Java对象进行分组,即Person.java
public class Person { String name; String surname; .... }
因此,如果我有n个 Person对象,那么最简单的方法是让所有人将“David”命名为Map<String, List> map;
?
我在Google上发现了这个(但它没有编译),它似乎是我正在寻找的东西: http : //www.anzaan.com/2010/06/grouping-objects-using-objects-property/
可能有一个库可以更简单地执行此操作,但手动执行并不困难:
List allPeople; // your list of all people Map> map = new HashMap>(); for (Person person : allPeople) { String key = person.getName(); if (map.get(key) == null) { map.put(key, new ArrayList ()); } map.get(key).add(person); } List davids = map.get("David");
将java-8与Collectors
类和流一起使用 ,您可以这样做:
Map> mapByName = allPeople.stream().collect(Collectors.groupingBy(Person::getName)); List allDavids = mapByName.getOrDefault("David", Collections.emptyList());
这里我使用了getOrDefault
这样如果原始列表中没有“David”,你就会得到一个空的不可变列表而不是null
引用,但如果你喜欢使用null
值,你可以使用get
。
希望能帮助到你! 🙂
Google Guava的Multimap完全符合您的需求,而且更多,避免了很多样板代码:
ListMultimap peopleByFirstName = ArrayListMultimap.create(); for (Person person : getAllPeople()) { peopleByFirstName.put(person.getName(), person); }
资料来源: http : //code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multimap
类似的东西(我没编译)
void addPerson(Person p, Map> map){ ArrayList lst = map.get(p.name); if(lst == null){ lst = new ArrayList (); } lst.add(p); map.put(p.name, lst); } ... for(Person p:personsCollection>){ addPerson(p, map); }
在Scala中,这已经是类List的一个特性:
class Person (val name: String, val surname: String ="Smith") val li = List (new Person ("David"), new Person ("Joe"), new Person ("Sue"), new Person ("David", "Miller")) li.groupBy (_.name)
res87:scala.collection.immutable.Map [String,List [Person]] = Map((David,List(Person @ 1c3f810,Person @ 139ba37)),(Sue,List(Person @ 11471c6)),(Joe,List (人@ d320e4)))
由于Scala与Java的字节码兼容,因此如果包含scala-jar,则应该能够从Java调用该方法。
您可以使用Eclipse Collections中的 Multimap和groupBy()
MutableList allPeople = Lists.mutable.empty(); MutableListMultimap multimapByName = allPeople.groupBy(Person::getName);
如果您无法从List
更改allPeople的类型
List allPeople = new ArrayList<>(); MutableListMultimap multimapByName = ListAdapter.adapt(allPeople).groupBy(Person::getName);
注意:我是Eclipse Collections的贡献者。
首先,您应该在arraylist中添加Person.java的对象,稍后我们可以通过以下方式返回这些细节
public void addPerson(){
ArrayList presonList = new ArrayList();
for(int i = 0; i <= presonList.size(); i ++){
Person obj = presonList.get(i);
//现在在这里做个别变量的事情
}
}