我有一个MyObjects列表... MyObject {int id,String name}。现在我想将列表拆分为具有相同“id”值的子列表,任何人都可以建议这样做的有效方法。
答案 0 :(得分:10)
// 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);
}
答案 1 :(得分:8)
使用Guava:
ListMultimap<Integer, MyObject> myObjectsById = Multimaps.index(myObjects,
new Function<MyObject, Integer>() {
public Integer apply(MyObject myObject) {
return myObject.id;
}
});
答案 2 :(得分:5)
如果您使用的是JDK 1.8,则可以使用优雅的解决方案,如:
Map<Integer, List<MyObject>> myObjectsPerId =
myObjects.stream().collect(Collectors.groupingBy(MyObject::getId));
答案 3 :(得分:2)
循环浏览元素,检查其id
值,并将其放在Hashtable
中,并以id
为键。这就是O(N),这和你将获得的效率一样高。
答案 4 :(得分:2)
使用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())));
答案 5 :(得分:1)
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
}