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.