5

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]}

4
  • 5
    System.out.println(Arrays.toString(outputList.toArray()))? Commented Oct 9, 2021 at 5:50
  • since when are primites or arrays allowed in generics btw.? haven't kept up but would be interested in the java version where is started to be allowed Commented Oct 9, 2021 at 6:24
  • 3
    Since always. (Or at least, since Java 5 when generics were introduced.) Commented Oct 9, 2021 at 6:33
  • 2
    @HopefullyHelpful Ints are not allowed in generics, but arrays (even int arrays) are objects, and thus can be used in generics, and this has been the case since the introduction of generics. Commented Oct 9, 2021 at 6:50

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

3

You can do it by using StringBuffer class

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);
    StringBuffer output=new StringBuffer();
    for (int[] ints : outputList)  output.append(Arrays.toString(ints)).append(",");
    output.insert(0,"{");
    output.replace(output.capacity()-2,output.capacity()-1,"}");
    System.out.println(output);
 }

Output:

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

Comments

2

Solution

This one-liner should do it:

 System.out.println(list.stream().map(Arrays::toString)
                                 .collect(Collectors.joining(", ", "{", "}")));

(I have line-wrapped it for readability.)


Non-solutions

  1. Since you want the outer list to be enclosed in { ... } we can't use List::toString in the Stream solution above. Likewise, Arrays::deepToString is going to give us the wrong output.

    Obviously, this can be fixed using String::replace, but that strikes me as ugly. It is better to use the correct "enclosers" in the first place. (Or change the requirements!!)

  2. Calling Arrays::toString() on an int[][] produced using List::toArray will give you this:

     [[I@2a40cd94, [I@f4168b8]
    

    ... which is not even close to correct.

    Arrays::toString calls toString on the int[] objects, and array classes do not override the Object::toString implementation.

    Arrays::deepToString addresses that aspect of the problem.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.