很確定沒有一個java API的方法。然而,你可以寫:
// This assumes your list is sorted according to someValue()
// SomeValueType is the type of SomeObject.someValue()
public Map<SomeValueType, List<SomeObject>> partition(List<SomeObject> list) {
Object currValue = null;
HashMap<SomeValueType, LinkedList<SomeObject>> result = new HashMap<SomeValueType, LinkedList<SomeObject>>();
LinkedList<SomeObject> currList = null;
for (SomeObject obj : list) {
if (!obj.someValue().equals(currValue()) {
currValue = obj.someValue();
currList = new LinkedList<SomeObject>();
result.put(currValue, currList);
}
currList.add(obj);
}
}
這將返回子列表,一個HashMap
其中關鍵是someValue
和值是與之相關的分區列表。請注意,我沒有測試這個,所以不要複製代碼。
編輯:使這個返回hashmap而不是arraylist。
+1 - 到目前爲止唯一正確的答案,IMO :-) – 2010-11-01 23:05:38
+1,但如果它是一個數組,修改的二進制搜索(找到最後一個實例,而不是第一個)會更好大量數據) – st0le 2010-11-02 05:35:45