2010-10-01 32 views

Trả lời

9
// 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); 
} 
+0

nhờ giải pháp này trông tao nhã với tôi. – james

+1

+1 - để thụt lề mã đúng cách và thêm nhận xét –

2

Lặp qua các phần tử, kiểm tra giá trị id của chúng và đặt chúng trong một Hashtable với id làm khóa. Đó là O (N), đó là hiệu quả như bạn sẽ nhận được.

+0

Còn giá trị thì sao? –

+0

@Kirk - Điều đó phụ thuộc vào cách OP sẽ sử dụng nó. Với một đối tượng tầm thường như vậy có thể thuận tiện để có 'tên' là giá trị, tuy nhiên trong nhiều trường hợp sẽ có ý nghĩa hơn khi có giá trị là chính đối tượng: nó không phải là câu hỏi bạn có thể trả lời mà không có ngữ cảnh. –

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 
} 
+0

+1, giá trị là một danh sách. –

+0

tên không bao giờ trở thành không null trong giải pháp này trong trường hợp bạn phải thêm một ArrayList mới. –

+0

@Mark: Tôi đã không kiểm tra mã. Cảm ơn bạn đã chỉ ra. – Emil

8

Sử dụng Guava:

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

Hoặc, khi sử dụng Java 8: ListMultimap myObjectsById = Multimaps.index (myObjects, MyObject :: getId); Nhưng sau đó bạn cũng có thể bỏ qua Guava hoàn toàn và sử dụng câu trả lời của Damien O'Reilly –

2

Sử dụng 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()))); 
3

Nếu bạn đang sử dụng JDK 1.8, bạn có thể sử dụng một giải pháp thanh lịch như:

Map<Integer, List<MyObject>> myObjectsPerId = 
    myObjects.stream().collect(Collectors.groupingBy(MyObject::getId)); 
Các vấn đề liên quan