Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of int array in Java

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

like image 513
rickygrimes Avatar asked Oct 09 '21 05:10

rickygrimes


People also ask

Can you make an ArrayList of ints?

We cannot create an ArrayList of primitive types like int. We need to use the wrapper classes of these primitives. The ArrayList class provides convenient methods to add and fetch elements from the list.

Can you have a List of ints in Java?

Create List of Ints Using the Arrays Class in Java. Here, we used the asList() method of the Arrays class to create a list of integers. If you have an array of integers and want to get a list, use the asList() method.

How to convert int array to integer list in Java?

To get List<Integer>, we need to convert an array of primitive ints to the Integer array first. We can use the ArrayUtils.toObject () method provided by Apache Commons lang for conversion, as shown below: That’s all about converting int array to Integer List in Java.

How to get an array from a list in Java?

In the first line you create the object and in the constructor you pass an array parameter to List. In the second line you have all the methods of the List class: .get (...) Use Arrays.toString ( arl.get (0) ). List<int []> intArrays=new ArrayList<> (); int anExample []= {1,2,3}; intArrays.add (anExample);

How to get List<Integer> from an array of primitive INTs?

In order to get List<Integer>, we need to convert an array of primitive ints to Integer array first. We can use ArrayUtils.toObject () method provided by Apache Commons lang for conversion as shown below. 1 List<Integer> list = Arrays.asList(ArrayUtils.toObject(arr));

How do I create an int array with initial elements?

Depending on your needs you can also create an int array with initial elements like this: // (1) define your java int array int [] intArray = new int [] {4,5,6,7,8}; // (2) print the java int array for (int i=0; i<intArray.length; i++) { System.out.println (intArray [i]); }


Video Answer


3 Answers

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

like image 107
Arvind Kumar Avinash Avatar answered Oct 24 '22 21:10

Arvind Kumar Avinash


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]}
like image 3
Saurabh Dhage Avatar answered Oct 24 '22 22:10

Saurabh Dhage


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.

like image 2
Stephen C Avatar answered Oct 24 '22 22:10

Stephen C