【问题标题】:dividing arraylist into multiple arraylists将arraylist分成多个arraylist
【发布时间】:2012-07-16 01:24:18
【问题描述】:

我的程序根据一天中的时间创建一个包含 5000 到 60000 条记录的数组列表。我想将它拆分为尽可能多的数组列表,每个数组列表将有 1000 条记录。我在网上查看了许多示例并尝试了一些方法,但遇到了奇怪的问题。你能给我举个例子吗?

问候!

【问题讨论】:

  • 导致您出现问题的代码在哪里?

标签: java


【解决方案1】:
  public static <T> Collection<Collection<T>> split(Collection<T> bigCollection, int maxBatchSize) {
    Collection<Collection<T>> result = new ArrayList<Collection<T>>();

    ArrayList<T> currentBatch = null;
    for (T t : bigCollection) {
      if (currentBatch == null) {
        currentBatch = new ArrayList<T>();
      } else if (currentBatch.size() >= maxBatchSize) {
        result.add(currentBatch);
        currentBatch = new ArrayList<T>();
      }

      currentBatch.add(t);
    }

    if (currentBatch != null) {
      result.add(currentBatch);
    }

    return result;
  }

这是我们如何使用它(假设电子邮件是一个大的电子邮件地址数组列表:

Collection<Collection<String>> emailBatches = Helper.split(emails, 500);
    for (Collection<String> emailBatch : emailBatches) {
        sendEmails(emailBatch);
        // do something else...
        // and something else ...
    }
}

emailBatch 会像这样遍历集合:

private static void sendEmails(Collection<String> emailBatch){
    for(String email: emailBatch){
        // send email code here.
    }
}

【讨论】:

  • 看起来它可以工作,但我将如何从集合中提取数据?我以前从未使用过集合。
  • 你有。 :) ArrayList 是一个集合。您很可能希望遍历该集合。我添加了一个示例用法。
【解决方案2】:

您可以使用List 中的subList http://docs.oracle.com/javase/6/docs/api/java/util/List.html#subList 来拆分您的ArrayList。子列表将为您提供原始列表的视图。如果您真的想创建一个与旧列表分开的新列表,您可以执行以下操作:

int index = 0;
int increment = 1000;
while ( index < bigList.size() ) {
   newLists.add(new ArrayList<Record>(bigList.subList(index,index+increment));
   index += increment;
}

请注意,您必须在此处检查一个错误。这只是一个快速的伪代码示例。

【讨论】:

  • 我认为 OP 需要 5-60 个单独的 ArrayLists,每个包含 1000 条记录。不是 5-60 ArrayLists 提供相同数组 5000-60000 条记录的不同视图。
  • 该代码无法编译。我想你的意思是new ArrayList&lt;&gt;(bigList.subList(index, index+increment))
  • 感谢您的回答,这就是我现在所拥有的 pastebin.com/hEpXikws 但我收到以下运行时错误 java.lang.IndexOutOfBoundsException: toIndex = 29000 at java.util.SubList.(Unknown Source) at java.util.RandomAccessSubList.(Unknown Source) at java.util.AbstractList.subList(Unknown Source) at proxymanager.Main.main(Main.java:68)
猜你喜欢
  • 2014-08-17
  • 1970-01-01
  • 2014-12-29
  • 2011-02-23
  • 2016-07-01
  • 2018-08-16
  • 1970-01-01
  • 1970-01-01
  • 2016-02-22
相关资源
最近更新 更多