Java:如何在多个小型ArrayLists中拆分ArrayList?

ane*_*yzm 184 java arraylist

如何在相同大小(= 10)的多个ArrayLists中拆分ArrayList(size = 1000)?

ArrayList<Integer> results;
Run Code Online (Sandbox Code Playgroud)

pol*_*nts 312

您可以使用它subList(int fromIndex, int toIndex)来查看原始列表的一部分.

来自API:

返回指定的fromIndex,包含的和toIndex独占的列表部分的视图.(如果fromIndextoIndex相等,则返回的列表为空.)返回的列表由此列表支持,因此返回列表中的非结构更改将反映在此列表中,反之亦然.返回的列表支持此列表支持的所有可选列表操作.

例:

List<Integer> numbers = new ArrayList<Integer>(
    Arrays.asList(5,3,1,2,9,5,0,7)
);

List<Integer> head = numbers.subList(0, 4);
List<Integer> tail = numbers.subList(4, 8);
System.out.println(head); // prints "[5, 3, 1, 2]"
System.out.println(tail); // prints "[9, 5, 0, 7]"

Collections.sort(head);
System.out.println(numbers); // prints "[1, 2, 3, 5, 9, 5, 0, 7]"

tail.add(-1);
System.out.println(numbers); // prints "[1, 2, 3, 5, 9, 5, 0, 7, -1]"
Run Code Online (Sandbox Code Playgroud)

如果您需要这些切碎的列表不是视图,那么只需List从中创建一个新的subList.以下是将这些内容放在一起的示例:

// chops a list into non-view sublists of length L
static <T> List<List<T>> chopped(List<T> list, final int L) {
    List<List<T>> parts = new ArrayList<List<T>>();
    final int N = list.size();
    for (int i = 0; i < N; i += L) {
        parts.add(new ArrayList<T>(
            list.subList(i, Math.min(N, i + L)))
        );
    }
    return parts;
}


List<Integer> numbers = Collections.unmodifiableList(
    Arrays.asList(5,3,1,2,9,5,0,7)
);
List<List<Integer>> parts = chopped(numbers, 3);
System.out.println(parts); // prints "[[5, 3, 1], [2, 9, 5], [0, 7]]"
parts.get(0).add(-1);
System.out.println(parts); // prints "[[5, 3, 1, -1], [2, 9, 5], [0, 7]]"
System.out.println(numbers); // prints "[5, 3, 1, 2, 9, 5, 0, 7]" (unmodified!)
Run Code Online (Sandbox Code Playgroud)


Mik*_*e Q 201

您可以将Guava库添加到项目中,并使用Lists.partition方法,例如

List<Integer> bigList = ...
List<List<Integer>> smallerLists = Lists.partition(bigList, 10);
Run Code Online (Sandbox Code Playgroud)


joh*_*ieb 58

Apache Commons Collections 4在类中有一个分区方法ListUtils.以下是它的工作原理:

import org.apache.commons.collections4.ListUtils;
...

int targetSize = 100;
List<Integer> largeList = ...
List<List<Integer>> output = ListUtils.partition(largeList, targetSize);
Run Code Online (Sandbox Code Playgroud)


i00*_*174 34

Java8 流,一种表达式,没有其他库:

List<String> input = ...
int partitionSize = ...

 Collection<List<String>> partitionedList = IntStream.range(0, input.size())
    .boxed()
        .collect(Collectors.groupingBy(partition -> (partition / partitionSize), Collectors.mapping(elementIndex -> input.get(elementIndex), Collectors.toList())))
            .values();
Run Code Online (Sandbox Code Playgroud)

测试

List<String> input = Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h" ,"i");
Run Code Online (Sandbox Code Playgroud)

分区大小 = 1 -> [[a], [b], [c], [d], [e], [f], [g], [h], [I]]

分区大小 = 2 -> [[a, b], [c, d], [e, f], [g, h], [I]]

分区大小 = 3 -> [[a, b, c], [d, e, f], [g, h, I]]

分区大小 = 7 -> [[a, b, c, d, e, f, g], [h, I]]

分区大小 = 100 -> [[a、b、c、d、e、f、g、h、i]]

  • 这个答案被低估了。2021年底最干净的方法 (3认同)
  • 这是一个巧妙的技巧,但很难看出发生了什么。我不会用它。 (2认同)

Lar*_*ara 22

polygenelubricants提供的答案基于给定的大小分割数组.我正在寻找将数组拆分为给定数量的部分的代码.以下是我对代码所做的修改:

public static <T>List<List<T>> chopIntoParts( final List<T> ls, final int iParts )
{
    final List<List<T>> lsParts = new ArrayList<List<T>>();
    final int iChunkSize = ls.size() / iParts;
    int iLeftOver = ls.size() % iParts;
    int iTake = iChunkSize;

    for( int i = 0, iT = ls.size(); i < iT; i += iTake )
    {
        if( iLeftOver > 0 )
        {
            iLeftOver--;

            iTake = iChunkSize + 1;
        }
        else
        {
            iTake = iChunkSize;
        }

        lsParts.add( new ArrayList<T>( ls.subList( i, Math.min( iT, i + iTake ) ) ) );
    }

    return lsParts;
}
Run Code Online (Sandbox Code Playgroud)

希望它可以帮助某人.


J.R*_*J.R 14

这适合我

/**
* Returns List of the List argument passed to this function with size = chunkSize
* 
* @param largeList input list to be portioned
* @param chunkSize maximum size of each partition
* @param <T> Generic type of the List
* @return A list of Lists which is portioned from the original list 
*/
public static  <T> List<List<T>> chunkList(List<T> list, int chunkSize) {
    if (chunkSize <= 0) {
        throw new IllegalArgumentException("Invalid chunk size: " + chunkSize);
    }
    List<List<T>> chunkList = new ArrayList<>(list.size() / chunkSize);
    for (int i = 0; i < list.size(); i += chunkSize) {
        chunkList.add(list.subList(i, i + chunkSize >= list.size() ? list.size()-1 : i + chunkSize));
    }
    return chunkList;
}
Run Code Online (Sandbox Code Playgroud)

例如:

List<Integer> stringList = new ArrayList<>();
stringList.add(0);
stringList.add(1);
stringList.add(2);
stringList.add(3);
stringList.add(4);
stringList.add(5);
stringList.add(6);
stringList.add(7);
stringList.add(8);
stringList.add(9);

List<List<Integer>> chunkList = getChunkList1(stringList, 2);
Run Code Online (Sandbox Code Playgroud)

  • 请注意,这有一个错误,它忽略了最后一组数据。ex 201 分成 100 块将返回 100,100,0 而不是 100,100,1 (5认同)

i_a*_*ero 7

Java 8

我们可以根据一些大小或根据条件拆分列表。

static Collection<List<Integer>> partitionIntegerListBasedOnSize(List<Integer> inputList, int size) {
        return inputList.stream()
                .collect(Collectors.groupingBy(s -> (s-1)/size))
                .values();
}
static <T> Collection<List<T>> partitionBasedOnSize(List<T> inputList, int size) {
        final AtomicInteger counter = new AtomicInteger(0);
        return inputList.stream()
                    .collect(Collectors.groupingBy(s -> counter.getAndIncrement()/size))
                    .values();
}
static <T> Collection<List<T>> partitionBasedOnCondition(List<T> inputList, Predicate<T> condition) {
        return inputList.stream().collect(Collectors.partitioningBy(s-> (condition.test(s)))).values();
}
Run Code Online (Sandbox Code Playgroud)

然后我们可以将它们用作:

final List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
System.out.println(partitionIntegerListBasedOnSize(list, 4));  // [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10]]
System.out.println(partitionBasedOnSize(list, 4));  // [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10]]
System.out.println(partitionBasedOnSize(list, 3));  // [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
System.out.println(partitionBasedOnCondition(list, i -> i<6));  // [[6, 7, 8, 9, 10], [1, 2, 3, 4, 5]]
Run Code Online (Sandbox Code Playgroud)

  • @gooornik07 一个流只能使用一次。 (2认同)

use*_*696 5

private ArrayList<List<String>> chunkArrayList(ArrayList<String> arrayToChunk, int chunkSize) {
    ArrayList<List<String>> chunkList = new ArrayList<>();
    int guide = arrayToChunk.size();
    int index = 0;
    int tale = chunkSize;
    while (tale < arrayToChunk.size()){
            chunkList.add(arrayToChunk.subList(index, tale));
            guide = guide - chunkSize;
            index = index + chunkSize;
            tale = tale + chunkSize;
    }
    if (guide >0) {
       chunkList.add(arrayToChunk.subList(index, index + guide));
    }
    Log.i("Chunked Array: " , chunkList.toString());
    return chunkList;
}
Run Code Online (Sandbox Code Playgroud)

例子

    ArrayList<String> test = new ArrayList<>();
    for (int i=1; i<=1000; i++){
        test.add(String.valueOf(i));
    }

    chunkArrayList(test,10);
Run Code Online (Sandbox Code Playgroud)

输出

分块:: [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [11, 12, 13, 14, 15, 16, 17, 18, 19, 20], [21 , 22, 23, 24, 25, 26, 27, 28, 29, 30], [31, 32, 33, 34, 35, 36, 37, 38, 39, 40], [41, 42, 43, 44 , 45, 46, 47, 48, 49, 50], [51, 52, 53, 54, 55, 56, 57, 58, 59, 60], [61, 62, 63, 64, 65, 66, 67 , 68, 69, 70], [71, 72, 73, 74, 75, 76, 77, 78, 79, 80], [81, 82, 83, 84, 85, 86, 87, 88, 89, 90 ], [91, 92, 93, 94, 95, 96, 97, 98, 99, 100],........

你会在你的日志中看到