java 根据对象属性将java集合拆分为子集合
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3836621/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
split a java collection into sub collections based on a object property
提问by james
I have a List of MyObjects ... MyObject{ int id,String name}. Now I want to split the the list into sublists that have identical "id" values, can any one suggest an efficient approach for doing this.
我有一个 MyObjects 列表... MyObject{ int id,String name}。现在我想将列表拆分为具有相同“id”值的子列表,任何人都可以提出一种有效的方法来做到这一点。
回答by Mark Elliot
// create the thing to store the sub lists
Map<Integer, List<MyObject>> subs = new HashMap<Integer, List<MyObject>>();
// iterate through your objects
for(MyObject o : list){
// fetch the list for this object's id
List<MyObject> temp = subs.get(o.getId());
if(temp == null){
// if the list is null we haven't seen an
// object with this id before, so create
// a new list
temp = new ArrayList<MyObject>();
// and add it to the map
subs.put(o.getId(), temp);
}
// whether we got the list from the map
// or made a new one we need to add our
// object.
temp.add(o);
}
回答by Kevin Bourrillion
回答by Damien O'Reilly
If you are using JDK 1.8, you can use an elegant solution like:
如果您使用的是 JDK 1.8,则可以使用优雅的解决方案,例如:
Map<Integer, List<MyObject>> myObjectsPerId =
myObjects.stream().collect(Collectors.groupingBy(MyObject::getId));
回答by Ian Henry
Loop through the elements, check their id
values, and place them in a Hashtable
with id
as the key. That's O(N), which is as efficient as you're going to get.
循环遍历元素,检查它们的id
值,并将它们放在Hashtable
with 中id
作为键。那是 O(N),它与您将获得的效率一样高。
回答by Piotr
Using JDK 1.8:
使用 JDK 1.8:
List<MyObject> objects= new ArrayList();
Map<Integer, List<MyObject>> obejctMap = new HashMap();
objects.stream().map(MyObject::getId).distinct().forEach(id -> obejctMap .put(id,
objects.stream().filter(object -> id.equals(object.getId())).collect(Collectors.toList())));
回答by Emil
ArrayList<MyObject> list=new ArrayList<MyObject>();
//fill Objects..
HashMap<Integer,ArrayList<MyObject>> hash=new HashMap<Integer,ArrayList<MyObject>>();
for(MyObject elem:list)//iterate the list
{
ArrayList<MyObject> tmp=null; //temporary variable
if((tmp=hash.get(elem.getId()))==null) // check if id already present in map
{
tmp=new ArrayList<MyObject>();
hash.put(elem.getId(),tmp); //if not put a new array list
}
names.add(elem); //if present add the name to arraylist
}