javaarraylistiterationreverse

Java: how to reverse the order of every N elements in an ArrayList


I have an input text file of thousands of lines of words, where I would like write to the output file, where I reverse the order of every 10 lines. I have iterated over the entire text file, and stored it in an ArrayList<String> array and I am now trying to figure out how I can reverse the order of every 10 lines in the entire ArrayList.

so for example the output should be like this: Line : 10, 9, 8, 7 ...... 1, 20, 19, 18, 17.....11, 30, 29, 28, 27.....21 and so on until I have done this for the entire text file (Stored in the ArrayList). Below is the portion of code I have been using to try and reverse the lines as stated.

   for(int i = array.size()-1; i >= array.size()-10; i--){ 
     array.add(array.get(i));
   }

   for (String text : array) {
            w.println(text);
        }

 }

What I have so far, reads and reverses only the last 10 lines of the input file and writes it to the output file. I have been having trouble figuring out a way to iteratively achieve this type of pattern throughout the entire data set, making sure that I do not hit an index out of bounds error.


Solution

  • Use a simple streaming approach. This is basically the current solution applied every ten lines instead of once at the end.

    1. Read ten lines in.
    2. Reverse these lines1.
    3. Write the ten reversed lines out.
    4. Repeat until the entire file is processed.

    The only edge case is doing something appropriate at the end when the file isn't a multiple of 10 lines.

    This same streaming approach can be used to create a new each-10 reversed list. It only 'becomes complicated' when trying to mutating the original list.


    1 Steps 2 and 3 can be combined by iterating the list of ten lines backward when writing to the output.