Java中int数组的列表

ric*_*mes 5 java arrays string list

如何打印其中包含原始类型 int 对象的 List 的内容?最好将答案打印在一行中。这是我的代码。

public static void main(String[] args) {
    List<int[]> outputList = new ArrayList<>();
    int[] result = new int[] { 0, 1 };
    int[] result2 = new int[] { 2, 3 };
    outputList.add(result);
    outputList.add(result2);

    System.out.println(Arrays.toString(outputList.get(0)));
}
Run Code Online (Sandbox Code Playgroud)

这会给我 [0,1] 但我正在寻找 {[0,1],[2,3]}

Arv*_*ash 3

以下单行可以满足您的要求:

System.out.println(
                Arrays.deepToString(outputList.toArray()).replaceAll("(?<=^)\\[", "{").replaceAll("\\](?=$)", "}"));
Run Code Online (Sandbox Code Playgroud)

它使用正向lookbehind 和正向lookahead 正则表达式断言。请注意,^用于文本的开头,$用于文本的结尾。为Arrays.deepToString(outputList.toArray())我们提供了字符串,[[0, 1], [2, 3]]该解决方案[在此字符串的开头和]结尾处分别替换为{}

如果您还想删除所有空格,可以再链接一个替换,如下所示:

System.out.println(Arrays.deepToString(outputList.toArray()).replaceAll("(?<=^)\\[", "{")
            .replaceAll("\\](?=$)", "}").replace(" ", ""));
Run Code Online (Sandbox Code Playgroud)

演示:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String args[]) {
        List<int[]> outputList = new ArrayList<>();
        int[] result = new int[] { 0, 1 };
        int[] result2 = new int[] { 2, 3 };
        outputList.add(result);
        outputList.add(result2);

        System.out.println(
                Arrays.deepToString(outputList.toArray()).replaceAll("(?<=^)\\[", "{").replaceAll("\\](?=$)", "}"));

        System.out.println(Arrays.deepToString(outputList.toArray()).replaceAll("(?<=^)\\[", "{")
                .replaceAll("\\](?=$)", "}").replace(" ", ""));
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

{[0, 1], [2, 3]}
{[0,1],[2,3]}
Run Code Online (Sandbox Code Playgroud)

ONLINE DEMO