Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

integer array as arguments while running java jar

I have a simple question.How do i pass integer array as argument while running java -jar sample.jar.The integer array is my input.

There are some other options like passing the array as comma seperated values (like 1,2,3) and converting the string values as integer array in java.

I want to know if there is any other option. Thanks for the help!

like image 600
x_coder Avatar asked Dec 25 '22 15:12

x_coder


1 Answers

No, there are no other options really. The command line arguments simply are passed as text. Some code, somewhere, has to parse them into integers.

There are various third party libraries available to parse the command line, but your entry point is certainly going to have a String[] parameter. If all you need is an int[], I'd just convert each String into an int. In Java 8 this is really pretty simple:

import java.util.Arrays;

public class Test {
    public static void main(String[] args) {
        int[] array = Arrays.stream(args).mapToInt(Integer::parseInt).toArray();

        // Just for example
        for (int value : array) {
            System.out.println(value);
        }
    }
}
like image 137
Jon Skeet Avatar answered Jan 09 '23 17:01

Jon Skeet