开发者

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.


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++;
}


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.


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;

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜