很确定没有一个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