Ogen
Ogen

Reputation: 6709

How to format a string with a variable number of arguments

Lets say I have a method which returns a list with a random number of random numbers - we will call that method List<Integer> getRandomNumberOfRandomNumbers();

System.out.println(String.format("Here are the random numbers: %s", getRandomNumberOfRandomNumbers()));

I know this won't work but how can I achieve this effect?

Example Output

Here are the random numbers:

1 4 2 4

Here are the random numbers:

2 43 323 434 3423 54

Upvotes: 2

Views: 3543

Answers (3)

Wasi Ahmad
Wasi Ahmad

Reputation: 37691

For example, if we have a List of Integers as below:

List<Integer> var = new ArrayList<>();
var.add(1);
var.add(4);
var.add(2);
var.add(4);

Then to print the List in your desired way, you can follow this:

System.out.println(String.format("Here are the random numbers:%n%n%s",
                             var.toString().replaceAll("[,\\[,\\]]", "")));

This outputs:

Here are the random numbers:

1 4 2 4

Here var is the list your function getRandomNumberOfRandomNumbers() is returning and we are converting it to String using var.toString() but it returns [1, 4, 2, 4]. So, we need to remove [, ] and ,. I used regular expression to replace them with an empty character. This is actually simple and easy way but not sure whether it is an efficient way!! Whenever i need to convert a Colletion to String, i use toString() method and then do some trick with regular expression to get my desired form of representation.

Update: After surfing web, i found few alternatives. (Preferred over my previous answer using List.toString())

For example, in your case, you can do:

StringJoiner sj = new StringJoiner(" ");
for (Integer i : var) {
    sj.add(String.valueOf(i));
}
System.out.println(sj.toString());

You can do the same with the following two alternatives.

Upvotes: 3

Sam Yuyitung
Sam Yuyitung

Reputation: 71

Another solution is iterating through the list and adding the values to a string builder before printing it out

like so:

StringBuilder stringBuilder = new StringBuilder();
for(Integer number : getRandomNumberOfRandomNumbers())
    stringBuilder.append(number + " ");
System.out.println("Here are the random numbers: " + stringBuilder.toString().trim());

Upvotes: 0

Jeremy Gurr
Jeremy Gurr

Reputation: 1623

It's easiest to just make getRandomNumberOfRandomNumbers return all of the numbers in a single String. Or you could do it all inline, like this:

getRandomNumberOfRandomNumbers().stream()
    .map(Object::toString)
    .collect(Collectors.joining(" "));

Upvotes: 4

Related Questions