me123
me123

Reputation: 1503

How to read from set of arrays line by line in Java?

My code is as follows:

private static ArrayList<String[]> file;

...

void method()
{
  file = new ArrayList<String[]>();
  ...
  String[] s = str.split(";");
  file.add(s);
}

In the above, str is a long String that is seperated by semicolons.

My problem is that I want to go through each array in the ArrayList and get one element from each array.

So for example if one array was "hello; are; today" and another was "how; you;" then I want to retrieve it as "hello how are you today" (ie. one element from each array).

I can't think of a way to do this.

Any help will be much appreciated.

Thanks in advance.

Upvotes: 0

Views: 426

Answers (3)

Lijo
Lijo

Reputation: 6788

to read an array list we can use iterator interface.` using iterator we can go through the array list. this is just an example code.

public static void  main(String []args)
   {
      ArrayList<String[]>  list=new ArrayList<>();
      String arr1[]={"hello","are","today"};
        String arr2[]={"how","you"};
        list.add(arr1);
        list.add(arr2);
       Iterator<String[]> it = list.iterator();
         while(it.hasNext())
         {
             String[] temp=it.next();
             System.out.print(temp[0]+" ");

         }



   }`

output= hello how;

Upvotes: 0

Andreas Dolk
Andreas Dolk

Reputation: 114817

That's not too difficult - under the assumption, that all rows have equal size!!

private void dumpColumnwise() {

  // generate test input
  // String[] firstRow = {"a00", "a01", "a02"};
  // String[] secondRow = {"a10", "a11", "a12"};
  String[] firstRow = "a00;a01;a02".split(";");
  String[] secondRow = "a10;a11;a12".split(";");

  List<String[]> rows = new ArrayList<String[]>();
  rows.add(firstRow);
  rows.add(secondRow);

  // get longest row
  int numberOfColumns = 0;
  for (String[] row:rows) {
    numberOfColumns = Math.max(numberOfColumns, row.length);
  }

  int numberOfRows = rows.size();
  for (int column = 0; column < numberOfColumns; colunm++) {
    for (int row = 0; row < numberOfRows; row++) {
      String[] row = rows.get(row);
      if (column < row.length) {
        System.out.printf(" %s", rows.get(row)[column]);
      }
    } 
  }
}

Room for improvement: allow input data with different row lengths. In this case you have to (1) determine the longest row and (2) test if the column index is valid for the actual row. ... done.

Upvotes: 0

Bozho
Bozho

Reputation: 597382

int currentIndex = 0;
StringBuilder b = new StringBuilder();
boolean arraysHaveMoreElements = true;
while (arraysHaveMoreElements) {
    arraysHaveMoreElements = false;
    for (String[] array : file) {
        if (array.length > currentIndex) {
            b.append(array[currentIndex];
            arraysHaveMoreElements = true;
        }
    }
    currentIndex++;
}

Upvotes: 1

Related Questions