1

[Apples, Cheese, Eggs, Tea, Cheese, Tea, Apples, Cheese, Juice, Peppers, Tea, Apples, Cheese, Apples, Cheese, Peppers, Spinach, Tea, Apples, Cheese, Peppers, Tea, Apples, Peppers, Tea, Eggs, Peppers, Tea, Apples, Cheese, Peppers, Tea, Cheese, Eggs, Spinach, Apples, Spinach, Cheese, Spinach, Tea, Cheese, Peppers, Tea] - ArrayList items

[4, 2, 5, 2, 5, 1, 3, 3, 3, 4, 3, 2, 3, 3] - ArrayList numbers

I have these 2 separate arraylists above. I would like to add 4 of the words to a temporary arraylist, and then add that temp arraylist to a spot in a permanent arraylist. So that would be a 2D arraylist. That would be one iteration, then I would like to add 2 more words to the temp arraylist and then add the temp to the second spot in the permanent arraylist... and so on

my method returns a 2d arraylist called ListOfItems, and the method takes in 2 parameters, the arraylist of items (called items) and the arraylist of numbers (called numbers)

    int itemsIndex = 0;
    int numbersIndex = 0;
    for (int i = 0; i < items.size(); i++) {
        if (itemsIndex == numbers.get(numbersIndex)) {
            ListOfItems.add(itemSet);
            itemSet.clear();
            numbersIndex++;
        } else if (itemsIndex != numbers.get(numbersIndex)) {
            itemSet.add(items.get(itemsIndex));
            itemsIndex++;
        }
    }
    return ListOfItems;
  • 1
    I would recommend you to add some more other premises in your question regarding where this List is used and the version of java you are looking for. Your question is may duplicate and already answered with https://stackoverflow.com/questions/6536094/java-arraylist-copy – Rafael Gorski May 04 '19 at 21:31
  • Possible duplicate of [Java ArrayList copy](https://stackoverflow.com/questions/6536094/java-arraylist-copy) – Joey May 05 '19 at 00:01

1 Answers1

0

Something like this perhaps.

  List<String> items = List.of(
       "Apples", "Cheese", "Eggs", "Tea", "Cheese", "Tea", "Apples", "Cheese",
        "Juice", "Peppers", "Tea", "Apples", "Cheese", "Apples", "Cheese",     
        "Peppers", "Spinach", "Tea", "Apples", "Cheese", "Peppers", "Tea",     
        "Apples", "Peppers", "Tea", "Eggs", "Peppers", "Tea", "Apples",        
        "Cheese", "Peppers", "Tea", "Cheese", "Eggs", "Spinach", "Apples",     
        "Spinach", "Cheese", "Spinach", "Tea", "Cheese", "Peppers", "Tea");    

  List<Integer> numbers = List.of(4, 2, 5, 2, 5, 1, 3, 3, 3, 4, 3, 2, 3, 3);
  int start = 0;
  List<List<String>> list = new ArrayList<>();
  for (int end : numbers) {
     list.add(new ArrayList<>(items.subList(start, start + end)));
     start += end;
  }
  list.forEach(System.out::println);

Note that this presumes the sum of the numbers list equals the size of the items list.
WJS
  • 36,363
  • 4
  • 24
  • 39