package list.arraylist; import java.util.ArrayList; import java.util.List; /** * 此类实现了集合按某种规则分组的算法 * * @author xujt,2011-1-4 */ public class Group { /** * 分组 * * @param target * <code>List</code>待分组的集合 * @return <code>List</code>分组完成后的容器对象集合 */ public List<GroupContiner> group(List<MyObject> target) { List<GroupContiner> result = new ArrayList<GroupContiner>(); for (int i = 0; i < target.size(); i++) { MyObject myObject = target.get(i); target.remove(myObject); GroupContiner gc = new GroupContiner(); gc.getMyObjectList().add(myObject); for (int j = 0; j < target.size();) { MyObject _myObject = target.get(j); // 相同,分组,并加入到组容器集合 if (_myObject.getObjectId().equals(myObject.getObjectId())) { gc.getMyObjectList().add(_myObject); target.remove(_myObject); } else { j++; } } result.add(gc); } return result; } } /** * 集合中的存放的元素 * * @author xujt,2011-1-4 */ class MyObject { private String objectId = new String(); private String objectName = new String(); public String getObjectId() { return objectId; } public void setObjectId(String objectId) { this.objectId = objectId; } public String getObjectName() { return objectName; } public void setObjectName(String objectName) { this.objectName = objectName; } } /** * 分组后的容器,一个此对象代表一组数据 * * @author xujt,2011-1-4 */ class GroupContiner { private String objectId = new String(); private List<MyObject> myObjectList = new ArrayList<MyObject>(); public String getObjectId() { return objectId; } public void setObjectId(String objectId) { this.objectId = objectId; } public List<MyObject> getMyObjectList() { return myObjectList; } public void setMyObjectList(List<MyObject> myObjectList) { this.myObjectList = myObjectList; } }