[英]Use List.subList to perform element batching logic
我需要一個具有幾千個元素的ArrayList,並一次處理1000個元素。 所以我需要一個大的ArrayList(假設它有3500個元素)並創建具有1000個最大元素的新ArrayList。 我正在使用下面的代碼,但我覺得它效率不高,有什么建議嗎?
import java.util.ArrayList;
import java.util.List;
public class SubList {
public static void main(String[] args) {
List<Long> ids = new ArrayList<Long>();
for(int i=0; i<3500; i++){
ids.add(Long.valueOf(i));
}
int threashold=1000;
double iteration = (double)ids.size()/threashold;
int fromIndex=0;
int toIndex=threashold;
for(int i=0; i<iteration; i++){
if(i + 1 >= iteration){
toIndex = ids.size();
List<Long> list = ids.subList(fromIndex, toIndex);
processList(list);
}else{
List<Long> list = ids.subList(fromIndex, toIndex);
processList(list);
fromIndex += threashold;
toIndex += threashold;
}
}
}
private static void processList(List<Long> ids){
System.out.println("size=" + ids.size());
}
}
我在類ArrayList(表單openjdk)中檢查了方法子列表的實現。
public List<E> More ...subList(int fromIndex, int toIndex) {
subListRangeCheck(fromIndex, toIndex, size);
return new SubList(this, 0, fromIndex, toIndex);
}
返回的類不是ArrayList的實例,而是一個名為SubList的內部類的實例。
SubList(AbstractList<E> parent,
int offset, int fromIndex, int toIndex) {
this.parent = parent;
this.parentOffset = fromIndex;
this.offset = offset + fromIndex;
this.size = toIndex - fromIndex;
this.modCount = ArrayList.this.modCount;
}
SubList存儲與原始ArrayList的關系並使用它而不是制作簡單的副本,因此它應該與原始ArrayList一樣高效,並且子列表是在恆定時間內創建的。
所以,你的實現可能沒問題。
我用String列表做類似的事情。 我已將它轉換為Long為你。 它基本上是一個列表副本,除非它達到閾值,它存儲列表並啟動一個新列表。 它不像你的那樣處理內聯列表。 但這是一個“整潔”的方法..
public static List<List<Long>> getSubLists(List<Long> list, int size) {
List<List<Long>> outer = new ArrayList<List<Long>>();
List<Long> subList = new ArrayList<Long>(size);
for (Long l : list) {
subList.add(l);
if (subList.size() >= size) {
outer.add(subList);
subList = new ArrayList<Long>(size);
}
}
if (subList.size() > 0) {
outer.add(subList);
}
return outer;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.