2

I have a method that accepts any number of INTEGER parameters: pages(int,int...)

This method is to select some pages of PDF file.

Book Pages stored as a string type like this:

String pages = "1,2,3,6,9";

I want to make this string as the parameter of the method to look like:

pages(1,2,3,6,9);
2

2 Answers 2

3

This can be easily done with streams:

Stream
  .of(commaSeparated.split(","))
  .mapToInt(Integer::parseInt)
  .toArray();

You can combine this with varargs to get what you want:

public static void main (String[] args) {
  String commaSeparated = "0,1,2,3,4,5,6,7,8,9";
  int[] arguments =
    Stream
      .of(commaSeparated.split(","))
      .mapToInt(Integer::parseInt)
      .toArray();
  pages(arguments);
}

public static void pages(int... numbers) {
  System.out.println("numbers: " + Arrays.toString(numbers));
}

Output will be:

numbers: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Note: of course varargs isn't needed in this specific case, it's useful only if you plan to call the same method with a variable number of int arguments, otherwise you can just change its signature to pages(int[] numbers).

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

3 Comments

Thanks a lot, it works for me! as I'm new to programming and I'm using java in android programming. when I implement this solution it asked me to upgrade my language from v7 to v8 with lambda. what does it mean??
@IsamH.Abuaqlain It means that support for Streams was added starting from java 8 along with support for lambdas, so you can't use java 7 if you want to use Streams, you have to upgrade to java 8
Thanks, I appreciate it!
1

Do this :

public class Test {
   public static void main(String..args) {
        String pages = "1,2,3,6,9";
        String[] pagesArr = pages.split(",");
         pages(pagesArr);
   }

  static void pages(String... pagesArr) {
       int[] array = Arrays.asList(pagesArr).stream().mapToInt(Integer::parseInt).toArray();
       for (int i = 0; i < array.length; i++) {
            System.out.println(array[i]);
       }
   }
}

1 Comment

Nice answer! I like the other one as well. It does not convert the array to a List first since a stream can be made from an array.

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.