bernie2436
bernie2436

Reputation: 23911

Is there a way to create a collection of identical strings in java with one statement?

I want to create a queue of Strings that will have many identical elements in it (I'm simulating a set of program instructions). Is there any way to create this collection all at once with a single statement?

myQueue.addAll(create collection of x strings);

Otherwise, I'll obviously have to loop x times and call myqueue.add(String) x times.

Just wondering if there is a one-line instead of 3-line way to do this...

Thanks!

Upvotes: 1

Views: 58

Answers (3)

Matt McHenry
Matt McHenry

Reputation: 20929

Collections.nCopies(int n, T o) returns a List<T> containing n copies of the given object o.

Upvotes: 3

Pablo Moretti
Pablo Moretti

Reputation: 1434

myQueue.addAll(Arrays.asList(new String[]{"str", "str", "str"}));

Upvotes: 0

Juvanis
Juvanis

Reputation: 25950

myQueue.addAll(new String[]{"str", "str", "str"});

Upvotes: 0

Related Questions