Home > database >  List of int array in Java
List of int array in Java

Time:10-09

How do I print the contents of a List that contains a primitive type int object in it? Prefer answers to print this in one line. This is the code I have.

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

This will give me [0,1] but I am looking for {[0,1],[2,3]}

CodePudding user response:

You're printing it wrong. You are printing only element at index 0 which is [0,1].

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.toArray()))
}

CodePudding user response:

The following one-liner can meet your requirement:

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

It uses the positive lookbehind and positive lookahead regex assertions. Note that ^ is used for the start of the text and $ is used for the end of the text. The Arrays.deepToString(outputList.toArray()) gives us the string, [[0, 1], [2, 3]] and this solution replaces [ at the start of this string and ] at the end of this string, with { and } respectively.

In case, you want to remove all whitespace as well, you can chain one more replacement as follows:

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

Demo:

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(" ", ""));
    }
}

Output:

{[0, 1], [2, 3]}
{[0,1],[2,3]}

ONLINE DEMO

  • Related