Java fill array with N elements of a given string character (?)

Viewed 402

I want to generate this string:

?, ?, ?, ?, ?

I can generate it in PHP like this:

$s = implode(", ", array_fill(0, 5, "?"));

I can generate it in Python like this:

s = ", ".join(["?"] * 5)

I can generate it in Swift like this:

let s = Array(repeating: "?", count: 5).joined(separator: ", ")

But... how can I do it with Java? My initial guess is about using something like this:

String s = String.format("%s", String.join(", ", ...));

... and in those three dots end my happiness for now. If I resort to something like new StringBuilder(5) then I have to do .append("?") 5 times and then .toString() gives me a string (I'm looking for an array or a list of some sort). If I try something like Arrays.fill() it must work on an existing array (and I would like to do it in a one-liner if possible).

The idea for this is to compose a list of question-mark parameters to construct SQL statements like INSERT INTO %s (%) VALUES (%s); and give the placeholders their appropriate content before making a prepared statement and feeding it with data. I used 5 question marks as an example but it can be any number of question marks (one mark for each table column I want to specify in the insertion).

Can you give me a hint?

2 Answers

I believe String.join(", ", Collections.nCopies(5, "?")) should do the job. String.join puts it together with a delimeter, and Collections.nCopies makes an immutable List with the given element repeated n times (5 in this case).

It's just as easy in Java:

IntStream.range(0,5).mapToObj(x -> "?").collect(Collectors.joining(", "))
Related