0

私のプログラムは、時刻に応じて5000から60000レコードの配列リストを作成します。各配列リストに1000レコードが含まれるように、できるだけ多くの配列リストに分割したいと思います。私はオンラインで多くの例を見て、いくつかのことを試しましたが、奇妙な問題に遭遇しました。その一例を教えていただけますか?

よろしく!

4

2 に答える 2

2
  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;
  }

これが私たちがそれを使用する方法です(電子メールが電子メールアドレスの大きなArrayListであると仮定します:

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.
    }
}
于 2012-07-16T01:42:20.923 に答える
1

subList http://docs.oracle.com/javase/6/docs/api/java/util/List.html#subListfrom を使用しListてを分割できますArrayList。サブリストは、元のリストのビューを提供します。古いリストとは別に、本当に新しいリストを作成したい場合は、次のようにすることができます。

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

ここで1つのエラーでオフをチェックする必要があることに注意してください。これは簡単な擬似コードのサンプルです。

于 2012-07-16T01:27:31.720 に答える