2

I just wondering is it possible to use one array as a parameter instead of a few parameters at printf()?

Say like:

String[] strArr = {"Name","Address", "Mobile"};

//text = () -> strArr.getNext(); 

System.out.printf("%1$s %1$10s %1$10s", text);

I have feeling it should be possible.

my-
  • 604
  • 9
  • 17

3 Answers3

2

As per my comment, this, System.out.printf("%1$s %2$10s %3$10s", strArr); would work.

But another option is to use Java 8's streams which can be obtained from your array using java.util.Arrays.stream(...). For example:

Arrays.stream(strArr).forEach(e -> System.out.printf("%-15s", e));
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
1

If you want to replace:

System.out.printf("%1$s %2$10s %2$10s", "p1" "p2", "p3");

by

String[] strArr = {"p1", "p2", "p3"};
System.out.printf("%1$s %2$10s %2$10s", strArr );

It is possible, because java threats multi arguments as array

Can I pass an array as arguments to a method with variable arguments in Java?

Community
  • 1
  • 1
Dominik Kunicki
  • 1,037
  • 1
  • 12
  • 35
0

You can use Arrays.toString(Object[] a) as the javadoc says:

public static String toString(Object[] a)

Returns a string representation of the contents of the specified array. If the array contains other arrays as elements, they are converted to strings by the Object.toString() method inherited from Object, which describes their identities rather than their contents.

The value returned by this method is equal to the value that would be returned by Arrays.asList(a).toString(), unless a is null, in which case "null" is returned.

Cristofor
  • 2,077
  • 2
  • 15
  • 23