Java: Jak mogę podzielić ArrayList na wiele małych ArrayList?

Jak mogę podzielić ArrayList (size=1000) na wiele ArrayList o tym samym rozmiarze (=10) ?

ArrayList<Integer> results;
Author: Bo Persson, 2010-05-24

13 answers

Możesz użyć subList(int fromIndex, int toIndex) aby uzyskać widok części oryginalnej listy.

Z API:

Zwraca widok części tej listy pomiędzy podanymi fromIndex, inclusive i toIndex, exclusive. (Jeśli fromIndex i toIndex są równe, zwracana lista jest pusta.) Zwracana lista jest wspierana przez tę listę, więc zmiany niestrukturalne w zwracanej liście są odzwierciedlane na tej liście i vice-versa. Zwrócona lista obsługuje wszystkie opcjonalne operacje na liście obsługiwane przez tę listę.

Przykład:

    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]"

Jeśli chcesz, aby te listy nie były widokiem, po prostu utwórz nowy List z subList. Oto przykład złożenia kilku z tych rzeczy razem:

// 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!)
 272
Author: polygenelubricants,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-05-24 07:31:42

Możesz dodać bibliotekę Guava do swojego projektu i użyć List .metoda partycji , np.

List<Integer> bigList = ...
List<List<Integer>> smallerLists = Lists.partition(bigList, 10);
 169
Author: Mike Q,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-22 21:00:24

Apache Commons Collections 4 posiada metodę partycji w klasie ListUtils. Oto jak to działa:

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

int targetSize = 100;
List<Integer> largeList = ...
List<List<Integer>> output = ListUtils.partition(largeList, targetSize);
 46
Author: johnnieb,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-22 20:00:41

Odpowiedź udzielona przez polygenelubricants dzieli tablicę na podstawie podanego rozmiaru. Szukałem kodu, który podzieliłby tablicę na określoną liczbę części. Oto modyfikacja, którą zrobiłem w kodzie:

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;
}
Mam nadzieję, że to komuś pomoże.
 17
Author: Lara,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-10 09:03:57

To działa dla mnie

/**
* 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() : i + chunkSize));
    }
    return chunkList;
}

Eg:

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);
 7
Author: J.R,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-04 10:23:47

Zgaduję, że problem, który masz, polega na nazwaniu 100 ArrayLists i ich zaludnieniu. Możesz utworzyć tablicę ArrayLists i wypełnić każdą z nich za pomocą pętli.

Najprostszy (czyt. najgłupszy) sposób na zrobienie tego jest taki:

ArrayList results = new ArrayList(1000);
    // populate results here
    for (int i = 0; i < 1000; i++) {
        results.add(i);
    }
    ArrayList[] resultGroups = new ArrayList[100];
    // initialize all your small ArrayList groups
    for (int i = 0; i < 100; i++) {
            resultGroups[i] = new ArrayList();
    }
    // put your results into those arrays
    for (int i = 0; i < 1000; i++) {
       resultGroups[i/10].add(results.get(i));
    } 
 3
Author: angstrom91,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-05-24 07:36:37

Podobne pytanie zostało omówione tutaj, Java: podzielić listę na dwie podlisty?

Głównie możesz użyć sublist. Więcej szczegółów tutaj: subList

Zwraca widok części tej listy pomiędzy fromIndex, inclusive i toindex, exclusive. (Jeśli fromindex i toIndex są równe, zwracana lista jest pusta.) Zwracana lista jest wspierana przez tę listę, więc zmiany w zwracanej liście są odzwierciedlane na tej liście i vice-versa. Zwrócona lista obsługuje wszystkie opcjonalne operacje listy obsługiwane przez tę listę...

 3
Author: Incognito,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 11:54:59

Utwórz nową listę i dodaj sublist widok listy źródeł przy użyciu metody addAll, aby utworzyć nową sublist
List newList = new ArrayList(); nowa lista.addAll(węg.subList (startIndex, endIndex));

 2
Author: user688,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-26 04:16:06

Możesz również użyć biblioteki FunctionalJava - istnieje metoda partition dla List. Ta lib ma swoje własne typy kolekcji, można je konwertować do kolekcji java tam iz powrotem.

import fj.data.List;

java.util.List<String> javaList = Arrays.asList("a", "b", "c", "d" );

List<String> fList = Java.<String>Collection_List().f(javaList);

List<List<String> partitions = fList.partition(2);
 1
Author: Mikhail Golubtsov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-28 06:44:22
import org.apache.commons.collections4.ListUtils;
ArrayList<Integer> mainList = .............;
List<List<Integer>> multipleLists = ListUtils.partition(mainList,100);
int i=1;
for (List<Integer> indexedList : multipleLists){
  System.out.println("Values in List "+i);
  for (Integer value : indexedList)
    System.out.println(value);
i++;
}
 1
Author: Rahul Palakurthi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-27 09:12:36

Jeśli nie chcesz importować biblioteki Apache commons, wypróbuj ten prosty kod:

final static int MAX_ELEMENT = 20;

public static void main(final String[] args) {

    final List<String> list = new ArrayList<String>();

    for (int i = 1; i <= 161; i++) {
        list.add(String.valueOf(i));
        System.out.print("," + String.valueOf(i));
    }
    System.out.println("");
    System.out.println("### >>> ");
    final List<List<String>> result = splitList(list, MAX_ELEMENT);

    for (final List<String> entry : result) {
        System.out.println("------------------------");
        for (final String elm : entry) {
            System.out.println(elm);
        }
        System.out.println("------------------------");
    }

}

private static List<List<String>> splitList(final List<String> list, final int maxElement) {

    final List<List<String>> result = new ArrayList<List<String>>();

    final int div = list.size() / maxElement;

    System.out.println(div);

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

        final int startIndex = i * maxElement;

        if (startIndex >= list.size()) {
            return result;
        }

        final int endIndex = (i + 1) * maxElement;

        if (endIndex < list.size()) {
            result.add(list.subList(startIndex, endIndex));
        } else {
            result.add(list.subList(startIndex, list.size()));
        }

    }

    return result;
}
 0
Author: B.JAAFAR,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-22 11:19:44

Musisz znać rozmiar kawałka, o który dzielisz listę. Powiedzmy, że masz listę 108 entries i potrzebujesz rozmiaru 25. W ten sposób skończysz z 5 lists:

  • 4 posiadające 25 entries każdy;
  • 1 (piąty) mający 8 elements.

Kod:

public static void main(String[] args) {

        List<Integer> list = new ArrayList<Integer>();
        for (int i=0; i<108; i++){
            list.add(i);
        }
        int size= list.size();
        int j=0;
                List< List<Integer> > splittedList = new ArrayList<List<Integer>>()  ;
                List<Integer> tempList = new ArrayList<Integer>();
        for(j=0;j<size;j++){
            tempList.add(list.get(j));
        if((j+1)%25==0){
            // chunk of 25 created and clearing tempList
            splittedList.add(tempList);
            tempList = null;
            //intializing it again for new chunk 
            tempList = new ArrayList<Integer>();
        }
        }
        if(size%25!=0){
            //adding the remaining enteries 
            splittedList.add(tempList);
        }
        for (int k=0;k<splittedList.size(); k++){
            //(k+1) because we started from k=0
            System.out.println("Chunk number: "+(k+1)+" has elements = "+splittedList.get(k).size());
        }
    }
 0
Author: yogesh kumar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-10 10:27:33

Java 8

Możemy podzielić listę na podstawie jakiegoś rozmiaru lub warunku.

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();
}

Wtedy możemy użyć ich jako:

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]]
 0
Author: i_am_zero,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-14 08:56:07