基于对象属性将java集合拆分为子集合

我有一个MyObjects列表… MyObject {int id,String name}。 现在我想将列表拆分为具有相同“id”值的子列表,任何人都可以建议这样做的有效方法。

// create the thing to store the sub lists Map> subs = new HashMap>(); // iterate through your objects for(MyObject o : list){ // fetch the list for this object's id List 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(); // 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); } 

使用番石榴 :

 ListMultimap myObjectsById = Multimaps.index(myObjects, new Function() { public Integer apply(MyObject myObject) { return myObject.id; } }); 

如果您使用的是JDK 1.8,则可以使用以下优雅的解决方案:

 Map> myObjectsPerId = myObjects.stream().collect(Collectors.groupingBy(MyObject::getId)); 

循环遍历元素,检查它们的id值,并将它们放在一个以id为键的Hashtable 。 那就是O(N),这就像你将获得的那样高效。

使用JDK 1.8:

 List objects= new ArrayList(); Map> 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()))); 
 ArrayList list=new ArrayList(); //fill Objects.. HashMap> hash=new HashMap>(); for(MyObject elem:list)//iterate the list { ArrayList tmp=null; //temporary variable if((tmp=hash.get(elem.getId()))==null) // check if id already present in map { tmp=new ArrayList(); hash.put(elem.getId(),tmp); //if not put a new array list } names.add(elem); //if present add the name to arraylist }