【问题标题】:Best way to pull items from an array 10 at a time一次从数组中提取 10 个项目的最佳方法
【发布时间】:2016-05-20 09:02:43
【问题描述】:

我有一个 ArrayList 可以包含无限数量的对象。我需要一次拉出 10 个项目并对其进行操作。

我能想象的就是这个。

int batchAmount = 10;
for (int i = 0; i < fullList.size(); i += batchAmount) {
    List<List<object>> batchList = new ArrayList();
    batchList.add(fullList.subList(i, Math.min(i + batchAmount, fullList.size()));
    // Here I can do another for loop in batchList and do operations on each item
}

有什么想法吗?谢谢!

【问题讨论】:

  • 您的解决方案还不起作用?
  • 应该,但我想听听其他人对如何更好地实现这一点的看法。

标签: java android arrays algorithm


【解决方案1】:

你可以这样做:

int batchSize = 10;
ArrayList<Integer> batch = new ArrayList<Integer>();
for (int i = 0; i < fullList.size();i++) {
    batch.add(fullList.get(i));
    if (batch.size() % batchSize == 0 || i == (fullList.size()-1)) {
        //ToDo Process the batch;
        batch = new ArrayList<Integer>();
    }
}

您当前实现的问题是您在每次迭代时都创建了一个batchList,您需要在循环之外声明这个列表(batchList)。比如:

int batchAmount = 10;
List<List<object>> batchList = new ArrayList();
for (int i = 0; i < fullList.size(); i += batchAmount) {
    ArrayList batch = new ArrayList(fullList.subList(i, Math.min(i + batchAmount, fullList.size()));
    batchList.add(batch);
 }
 // at this point, batchList will contain a list of batches

【讨论】:

  • 感谢我的实现。我喜欢你的实现。
【解决方案2】:

Google 提供的Guava library 提供了不同的功能。

List<Integer> countUp = Ints.asList(1, 2, 3, 4, 5);
List<Integer> countDown = Lists.reverse(theList); // {5, 4, 3, 2, 1}

List<List<Integer>> parts = Lists.partition(countUp, 2); // {{1, 2}, {3, 4}, {5}}

答案来自https://stackoverflow.com/a/9534034/3027124https://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained#Lists

希望这会有所帮助。

【讨论】:

    【解决方案3】:

    从 ArrayList 中提取元素:ArrayList.remove(0)

    // clone the list first if you need the values in the future:
    ArrayList<object> cloned = new ArrayList<>(list);
    while(!list.isEmpty()){
        object[] tmp = new object[10];
        try{
            for(int i = 0; i < 10; i++) tmp[i] = list.remove(0);
        }catch(IndexOutOfBoundsException e){
            // end of list reached. for loop is auto broken. no need to do anything.
        }
        // do something with tmp, whose .length is <=10
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-27
      • 2016-02-04
      • 2010-09-18
      • 1970-01-01
      • 2013-10-30
      • 1970-01-01
      • 2021-12-12
      • 1970-01-01
      相关资源
      最近更新 更多