English 中文(简体)
Java:如何扭转阿雷拉列斯群岛每个民族的秩序
原标题:Java: how to reverse the order of every N elements in an ArrayList

我有数千字的输入文本,我想在产出档案中写上,我改变了每10条线路的顺序。 我对全文进行了编辑,将其储存在<代码>上。 ArrayList<String> protocol,我现在试图说明我如何能够扭转整个阿雷拉派10条线路的次序。

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.

最佳回答

采用简单的主流化方法。 这基本上是目前采用的every10条线而不是最后一条线。

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

唯一一个最先进的案件是在档案中标有10条线的两条线的末尾进行的。

这种递解办法可用于编制new每10份倒置清单。 只有在试图改变原来的名单时,才变得复杂。


<>1> 步骤2和步骤3可以通过在撰写产出时将10条线清单重新排列。

问题回答

Two approaches:

  1. If it is already in memory, in an ArrayList, simply update that list.
  2. If not already in memory, process 10 lines at a time.
    This allows infinitely large data to be processed without running out of memory.

备选案文1

List<String> list = new ArrayList<>();
// code filling list

for (int i = 0; i < list.size(); i += 10) {
    int endOfBlock = Math.min(i + 10, list.size());
    for (int j = i, k = endOfBlock - 1; j < k; j++, k--) {
        String temp = list.get(j);
        list.set(j, list.get(k));
        list.set(k, temp);
    }
}

Option 2.

try (BufferedReader in = new BufferedReader(new FileReader(inFile)),
     PrintWriter out = new PrintWriter(new FileWriter(outFile))) {
    String[] buf = new String[10];
    int len = 0;
    for (String line; (line = in.readLine()) != null; ) {
        buf[len++] = line;
        if (len == 10) {
            while (len > 0)
                out.println(buf[--len]);
        }
    }
    while (len > 0)
        out.println(buf[--len]);
}

引言

    for (int i = 0, size = array.size(); i < size; i += 10)
        for (int from = i, to = Math.min(i + 10, size); from < to;)
            Collections.swap(array, from++, --to);

采用二级反变量,如果说明要检查约束,例如:

while(counter<array.size()+10)
    int counter = 9; //since index 9 is the 10th line
    for(int i=counter; i>counter-10; i--){
        if(i<array.size()){
            array.add(array.get(i));
        }
    }
    counter+=10;
}
for (String text : array){
        w.println(text);
}

我在此的唯一关切是,你似乎只是继续增加现有阵列,而不是重新排列,或是增加新阵列的内容?

此处使用 Java 22 预科语言

// [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22]
List<String> lines = IntStream.range(1, 22).mapToObj(Integer::toString).toList();

// [10,9,8,7,6,5,4,3,2,1,20,19,18,17,16,15,14,13,12,11,22,21]
List<String> output = list.stream()
        .gather(Gatherers.windowFixed(10))
        .flatMap(window -> window.reversed().stream())
        .toList();

使用了新的>>>>。 https://download.java.net/java/early_access/jdk22/docs/api/java.base/java/util/stream/Gatherers.html#windowFixed(int) rel=“nofollow noreferer”>Gatherers.windowFixed 召集人将清单分成10个项目。

Walkthrough

  1. Convert the List<String> to a Stream<String>.
    // [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22]
    lines.stream()
    
  2. Gather the elements into windows with 10 elements (or fewer, if at the end of the stream). This results in a Stream<List<String>>.
    // [[1,2,3,4,5,6,7,8,9,10],[11,12,13,14,15,16,17,18,19,20],[21,22]]
    .gather(Gatherers.windowFixed(10))
    
  3. Reverse each window, and then flatten it. This converts back to Stream<String>.
    // [10,9,8,7,6,5,4,3,2,1,20,19,18,17,16,15,14,13,12,11,22,21]
    .flatMap(window -> window.reversed().stream())
    
  4. Convert the Stream<String> to a List<String>.
    // [10,9,8,7,6,5,4,3,2,1,20,19,18,17,16,15,14,13,12,11,22,21]
    .toList()
    

Javadocs

rel=“nofollow noreferer”>>:

An intermediate operation that transforms a stream of input elements into a stream of output elements, optionally applying a final action when the end of the upstream is reached. […]

[…]

收集业务有许多例子,包括但不限于:将各种要素归类为批量(缩小功能);重复连续复制类似内容;增量积累功能(固定扫描);增量重订功能等。 :提供共同收集业务的实施。

Stream.gather<>::

回归包括将特定召集人应用到这一流要素的结果。

>: 密码>;Gatherers.windowFixed

• 返回一个把部件聚集到窗户的召集人——一组有固定规模的内容。 如果溪流空,就不会生产窗户。 最后一个窗口所含元素可能少于所提供的窗口规模。

例:

// will contain: [[1, 2, 3], [4, 5, 6], [7, 8]]
List<List<Integer>> windows =
    Stream.of(1,2,3,4,5,6,7,8).gather(Gatherers.windowFixed(3)).toList();




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签