リストをバッチに分割する一般的なJavaユーティリティはありますか?


140

リストを所定のサイズのバッチに分割するユーティリティを自分で作成しました。このためのapache commons utilがすでに存在するかどうかを知りたかっただけです。

public static <T> List<List<T>> getBatches(List<T> collection,int batchSize){
    int i = 0;
    List<List<T>> batches = new ArrayList<List<T>>();
    while(i<collection.size()){
        int nextInc = Math.min(collection.size()-i,batchSize);
        List<T> batch = collection.subList(i,i+nextInc);
        batches.add(batch);
        i = i + nextInc;
    }

    return batches;
}

すでに同じユーティリティが存在するかどうかをお知らせください。


4
これが主題外であるかどうかはわかりません。問題は、「どのライブラリがこれを行うか」ではなく、「Apache common utilsでこれをどのように実行できるか」です。
フロリアンF

@FlorianF同意します。この質問とその回答は非常に有用であり、小さな編集で十分に保存できます。それを急いで閉じるのは怠惰な行動でした。
Endery 2018

ここで素敵なクラスとベンチマークで有用なブログ記事を見つけました:e.printstacktrace.blog/...
Benj

回答:


249

Google Guavaからチェックアウト: Lists.partition(java.util.List, int)

同じサイズのリストの連続したサブリストを返します(最終的なリストはそれよりも小さい場合があります)。例えば、含有リスト区画[a, b, c, d, e]3つの歩留まりのパーティションサイズで[[a, b, c][d, e]]3と二つの要素の2つの内側のリストを含む外側のリスト、すべてのオリジナルの順序で- 。


リンク partition documentationリンク code example
オースティンハウズ

16
apacheの共通のユーザーのために、機能も利用可能です:commons.apache.org/proper/commons-collections/apidocs/org/...
ザビエルPortebois

3
リストを使用している場合は、「Apache Commons Collections 4」ライブラリを使用します。ListUtilsクラスにパーティションメソッドがあります。... int targetSize = 100; List <Integer> largeList = ... List <List <Integer >> output = ListUtils.partition(largeList、targetSize); このメソッドは、code.google.com
p /

1
ありがとうございました。これがJavaでどれほど難しいかは信じられません。
叔父のロングヘア

51

バッチのJava-8ストリームを作成する場合は、次のコードを試すことができます。

public static <T> Stream<List<T>> batches(List<T> source, int length) {
    if (length <= 0)
        throw new IllegalArgumentException("length = " + length);
    int size = source.size();
    if (size <= 0)
        return Stream.empty();
    int fullChunks = (size - 1) / length;
    return IntStream.range(0, fullChunks + 1).mapToObj(
        n -> source.subList(n * length, n == fullChunks ? size : (n + 1) * length));
}

public static void main(String[] args) {
    List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14);

    System.out.println("By 3:");
    batches(list, 3).forEach(System.out::println);

    System.out.println("By 4:");
    batches(list, 4).forEach(System.out::println);
}

出力:

By 3:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
[10, 11, 12]
[13, 14]
By 4:
[1, 2, 3, 4]
[5, 6, 7, 8]
[9, 10, 11, 12]
[13, 14]

このアプローチでどのように中断、続行、または復帰しますか?
ミラル

15

別のアプローチはCollectors.groupingBy、インデックスを使用してから、グループ化されたインデックスを実際の要素にマッピングすることです。

    final List<Integer> numbers = range(1, 12)
            .boxed()
            .collect(toList());
    System.out.println(numbers);

    final List<List<Integer>> groups = range(0, numbers.size())
            .boxed()
            .collect(groupingBy(index -> index / 4))
            .values()
            .stream()
            .map(indices -> indices
                    .stream()
                    .map(numbers::get)
                    .collect(toList()))
            .collect(toList());
    System.out.println(groups);

出力:

[1、2、3、4、5、6、7、8、9、10、11]

[[1、2、3、4]、[5、6、7、8]、[9、10、11]]


1
@Sebienこれは一般的なケースで機能します。groupingBy要素で行われIntStream.range、ないリスト要素。たとえばideone.com/KYBc7hを参照してください。
Radiodef

@MohammedElrashidy Sebienがコメントを削除しました。今すぐコメントを削除できます。
アルバートヘンドリックス

7

私はこれを思いつきました:

private static <T> List<List<T>> partition(Collection<T> members, int maxSize)
{
    List<List<T>> res = new ArrayList<>();

    List<T> internal = new ArrayList<>();

    for (T member : members)
    {
        internal.add(member);

        if (internal.size() == maxSize)
        {
            res.add(internal);
            internal = new ArrayList<>();
        }
    }
    if (internal.isEmpty() == false)
    {
        res.add(internal);
    }
    return res;
}

6

Java 9 IntStream.iterate()ではhasNext条件付きで使用できます。したがって、メソッドのコードを次のように簡略化できます。

public static <T> List<List<T>> getBatches(List<T> collection, int batchSize) {
    return IntStream.iterate(0, i -> i < collection.size(), i -> i + batchSize)
            .mapToObj(i -> collection.subList(i, Math.min(i + batchSize, collection.size())))
            .collect(Collectors.toList());
}

を使用する{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}と、結果は次のgetBatches(numbers, 4)ようになります。

[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9]]

5

次の例は、リストのチャンク化を示しています。

package de.thomasdarimont.labs;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SplitIntoChunks {

    public static void main(String[] args) {

        List<Integer> ints = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);

        List<List<Integer>> chunks = chunk(ints, 4);

        System.out.printf("Ints:   %s%n", ints);
        System.out.printf("Chunks: %s%n", chunks);
    }

    public static <T> List<List<T>> chunk(List<T> input, int chunkSize) {

        int inputSize = input.size();
        int chunkCount = (int) Math.ceil(inputSize / (double) chunkSize);

        Map<Integer, List<T>> map = new HashMap<>(chunkCount);
        List<List<T>> chunks = new ArrayList<>(chunkCount);

        for (int i = 0; i < inputSize; i++) {

            map.computeIfAbsent(i / chunkSize, (ignore) -> {

                List<T> chunk = new ArrayList<>();
                chunks.add(chunk);
                return chunk;

            }).add(input.get(i));
        }

        return chunks;
    }
}

出力:

Ints:   [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
Chunks: [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11]]

4

この質問の複製であるとクローズされた別の質問がありましたが、よく読んでみると微妙に異なります。したがって、誰か(私のような)が実際にリストをほぼ同じサイズのサブリストの指定された数に分割したい場合、次に進みます。

ここで説明したアルゴリズムをJavaに移植しただけです。

@Test
public void shouldPartitionListIntoAlmostEquallySizedSublists() {

    List<String> list = Arrays.asList("a", "b", "c", "d", "e", "f", "g");
    int numberOfPartitions = 3;

    List<List<String>> split = IntStream.range(0, numberOfPartitions).boxed()
            .map(i -> list.subList(
                    partitionOffset(list.size(), numberOfPartitions, i),
                    partitionOffset(list.size(), numberOfPartitions, i + 1)))
            .collect(toList());

    assertThat(split, hasSize(numberOfPartitions));
    assertEquals(list.size(), split.stream().flatMap(Collection::stream).count());
    assertThat(split, hasItems(Arrays.asList("a", "b", "c"), Arrays.asList("d", "e"), Arrays.asList("f", "g")));
}

private static int partitionOffset(int length, int numberOfPartitions, int partitionIndex) {
    return partitionIndex * (length / numberOfPartitions) + Math.min(partitionIndex, length % numberOfPartitions);
}


3

Webのさまざまなチートを使用して、私はこの解決策を見つけました:

int[] count = new int[1];
final int CHUNK_SIZE = 500;
Map<Integer, List<Long>> chunkedUsers = users.stream().collect( Collectors.groupingBy( 
    user -> {
        count[0]++;
        return Math.floorDiv( count[0], CHUNK_SIZE );
    } )
);

countを使用して、通常のコレクションインデックスを模倣します。
次に、代数商をバケット番号として使用して、コレクション要素をバケットにグループ化します。
最終的なマップには、キーとしてバケット番号がとして含まれますバケット自体。

その後、次のコマンドを使用して、各バケットで簡単に操作を実行できます。

chunkedUsers.values().forEach( ... );

4
AtomicIntegerforカウントを使用できます。
jkschneider 2017年

1
List<T> batch = collection.subList(i,i+nextInc);
->
List<T> batch = collection.subList(i, i = i + nextInc);

1

ストリームとライブラリなしのOPに似ていますが、簡潔に記述できます。

public <T> List<List<T>> getBatches(List<T> collection, int batchSize) {
    List<List<T>> batches = new ArrayList<>();
    for (int i = 0; i < collection.size(); i += batchSize) {
        batches.add(collection.subList(i, Math.min(i + batchSize, collection.size())));
    }
    return batches;
}

0

これを解決する別のアプローチ、質問:

public class CollectionUtils {

    /**
    * Splits the collection into lists with given batch size
    * @param collection to split in to batches
    * @param batchsize size of the batch
    * @param <T> it maintains the input type to output type
    * @return nested list
    */
    public static <T> List<List<T>> makeBatch(Collection<T> collection, int batchsize) {

        List<List<T>> totalArrayList = new ArrayList<>();
        List<T> tempItems = new ArrayList<>();

        Iterator<T> iterator = collection.iterator();

        for (int i = 0; i < collection.size(); i++) {
            tempItems.add(iterator.next());
            if ((i+1) % batchsize == 0) {
                totalArrayList.add(tempItems);
                tempItems = new ArrayList<>();
            }
        }

        if (tempItems.size() > 0) {
            totalArrayList.add(tempItems);
        }

        return totalArrayList;
    }

}

0

Java 8のワンライナーは次のようになります。

import static java.util.function.Function.identity;
import static java.util.stream.Collectors.*;

private static <T> Collection<List<T>> partition(List<T> xs, int size) {
    return IntStream.range(0, xs.size())
            .boxed()
            .collect(collectingAndThen(toMap(identity(), xs::get), Map::entrySet))
            .stream()
            .collect(groupingBy(x -> x.getKey() / size, mapping(Map.Entry::getValue, toList())))
            .values();

}

0

Java 8以降の簡単なソリューションを次に示します。

public static <T> Collection<List<T>> prepareChunks(List<T> inputList, int chunkSize) {
    AtomicInteger counter = new AtomicInteger();
    return inputList.stream().collect(Collectors.groupingBy(it -> counter.getAndIncrement() / chunkSize)).values();
}

0

以下のコードを使用して、リストのバッチを取得できます。

Iterable<List<T>> batchIds = Iterables.partition(list, batchSize);

上記のコードを使用するには、Google Guavaライブラリをインポートする必要があります。


-1

import com.google.common.collect.Lists;

List<List<T>> batches = Lists.partition(List<T>,batchSize)

Lists.partition(List、batchSize)を使用します。ListsGoogle共通パッケージ(com.google.common.collect.Lists)からインポートする必要があります

のリストList<T>と、に等しいすべての要素のサイズを返しますbatchSize


独自のsubList(startIndex, endIndex)方法を使用して、必要なインデックスに基づいてリストを分割することもできます。
v87278
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.