Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split a java collection into sub collections based on a object property

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.

like image 610
james Avatar asked Oct 01 '10 04:10

james


3 Answers

If you are using JDK 1.8, you can use an elegant solution like:

Map<Integer, List<MyObject>> myObjectsPerId =
    myObjects.stream().collect(Collectors.groupingBy(MyObject::getId));
like image 54
Damien O'Reilly Avatar answered Nov 20 '22 11:11

Damien O'Reilly


// 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);
}
like image 26
Mark Elliot Avatar answered Nov 20 '22 10:11

Mark Elliot


Using Guava:

ListMultimap<Integer, MyObject> myObjectsById = Multimaps.index(myObjects,
    new Function<MyObject, Integer>() {
      public Integer apply(MyObject myObject) {
        return myObject.id;
      }
    });
like image 8
Kevin Bourrillion Avatar answered Nov 20 '22 10:11

Kevin Bourrillion