Creating a list with repeating element

Java

Java Problem Overview


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"])?

Java Solutions


Solution 1 - Java

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]

Solution 2 - Java

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]);

Solution 3 - Java

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)

Solution 4 - Java

Version you can use for primitive arrays(Java 8):

DoubleStream.generate(() -> 123.42).limit(777).toArray(); // returns array of 777 123.42 double vals

Note that it returns double[], not Double[]

Works for IntegerStream, DoubleStream, LongStream

UPD

and for string dups you can use:

Stream.generate(() -> "value").limit(400).toArray()

No extra libs required, single line

Solution 5 - Java

Using IntStream, you can generate a range of integers, map them to the element you want and collect it as a list.

List<String> list = IntStream.rangeClosed(0, 5)
            .mapToObj(i -> "foo")
            .collect(Collectors.toList());

Or, as an array

 String[] arr = IntStream.rangeClosed(0, 5)
            .mapToObj(i -> "foo")
            .toArray(String[]::new);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionlaurtView Question on Stackoverflow
Solution 1 - JavaarshajiiView Answer on Stackoverflow
Solution 2 - JavaRené LinkView Answer on Stackoverflow
Solution 3 - JavahohsergView Answer on Stackoverflow
Solution 4 - JavamaxpovverView Answer on Stackoverflow
Solution 5 - Javauser7View Answer on Stackoverflow