Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a list with repeating element

Tags:

java

Is there an utility method in Java that generates a list or array of a specified length with all elements equal to a specified value (e.g ["foo", "foo", "foo", "foo", "foo"])?

like image 496
laurt Avatar asked Oct 10 '14 12:10

laurt


3 Answers

You can use Collections.nCopies. Note that this copies the reference to the given object, not the object itself. If you're working with strings, it won't matter because they're immutable anyway.

List<String> list = Collections.nCopies(5, "foo");
System.out.println(list);
[foo, foo, foo, foo, foo]
like image 69
arshajii Avatar answered Nov 10 '22 23:11

arshajii


For an array you can use Arrays.fill(Object[] a, Object val)

String[] strArray = new String[10];
Arrays.fill(strArray, "foo");

and if you need a list, just use

List<String> asList = Arrays.asList(strArray);

Then I have to use two lines: String[] strArray = new String[5]; Arrays.fill(strArray, "foo");. Is there a one-line solution?

You can use Collections.nCopies(5, "foo") as a one-line solution to get a list :

List<String> strArray = Collections.nCopies(5, "foo");

or combine it with toArray to get an array.

String[] strArray = Collections.nCopies(5, "foo").toArray(new String[5]);
like image 29
René Link Avatar answered Nov 11 '22 00:11

René Link


If your object are not immutable or not reference-transparent, you can use

Stream.generate(YourClass::new).limit(<count>)

and collect it to list

.collect(Collectors.toList())

or to array

.toArray(YourClass[]::new)
like image 17
hohserg Avatar answered Nov 10 '22 23:11

hohserg