0

I have code that is storing Strings in a ArrayList

ArrayList<String> cars = new  ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
cars.add("Honda");
cars.add("Tesla");

Is there a way for the out put to be

Volvo, BMW

Ford, Mazda

Honda, Tesla

and not [Volvo, BMW, Ford, Mazda, Honda, Tesla]

my problem is every n elements, not just 2

My thought was to make a new String for every n elements than store that in an Array

Wolf22
  • 21
  • 5

3 Answers3

0

Assuming you just need the output to be formatted that way, this could work using modulo. For each multiple of n, print a new line instead of a comma. Like so:

ArrayList<String> cars = new  ArrayList<String>();
        cars.add("Volvo");
        cars.add("BMW");
        cars.add("Ford");
        cars.add("Mazda");
        cars.add("Honda");
        cars.add("Tesla");
        int n = 2; //this can be changed with user input
        for (int i = 0; i < cars.size(); i++)
        {
            System.out.print(cars.get(i));
            if ((i+1) % n == 0)
            {
                System.out.println();
            }
            else
            {
                System.out.print(", ");
            }
        }
0

Depending on how you would like to output the result you could simply use a sublist.

 ArrayList<String> cars2 = new ArrayList<String>(cars.subList(1, 2));
0

In code below, sub list will be list of every n elements of cars.

ArrayList<String> cars = new ArrayList<>();
        int n = 2;
        for(int i = 0; i < (cars.size()+1)/n; i++) {
            int lastIndex = (i*n)+n;
            if(lastIndex > cars.size()) {
                lastIndex = cars.size();
            }
            ArrayList<String> subList = (ArrayList<String>) cars.subList(i*n, lastIndex);
            System.out.println(subList);
        }
Taha Malik
  • 2,188
  • 1
  • 17
  • 28