Alexey Shabramov Alexey Shabramov - 1 year ago 107
Java Question

Java 8 - what is the correct way to fill an arraylist with the same object using Stream API?

I am new with Stream API and I am looking for more elegant and shortest way to fill an ArrayList with the same object using Stream API equivalent to this code:

SomeObject someObject = new SomeObject();
List<SomeObject> someObjectList = new ArrayList<>();

int maxLimitValue = 70; //for example
for(int i=0; i<=maxLimitValue; i++){

I have seen many different solutions for my current task:

This variant is almost what I want, but there is an auto-generation of the objects, but I need to use the same object created once.

This solution is also almost what I need, but I am no sure about this copying of objects and the returned List type is not ArrayList (it returned the CopiesList type, which cannot be added to the ArrayList in the future operations).

p.s. maybe it's possible duplicate, but I really can't find the correct and short way to do this using Stream API.

Update (assylias additions):

Yes, I agree with you about this variant:

List<SomeObject> list = Collections.nCopies(70, someObject);

But, when I am opening this method:

public static <T> List<T> nCopies(int n, T o) {
if (n < 0)
throw new IllegalArgumentException("List length = " + n);
return new CopiesList<>(n, o);

And as we see - it returning the CopiesList object, not ArrayList.
Also, as the other lists, it is extending the AbstractList:

private static class CopiesList<E>
extends AbstractList<E>
implements RandomAccess, Serializable
private static final long serialVersionUID = 2739099268398711800L;

final int n;
final E element;

CopiesList(int n, E e) {
assert n >= 0;
this.n = n;
element = e;

It's not quite ArrayList, but thank's for your suggestions and advice whithout an empty words and off-topic comments, I will use your solution.

Answer Source

You can build the stream manually:

List<SomeObject> list = Stream.generate(() -> someObject).limit(70).collect(toList());

Although creating a stream just for that purpose is probably inefficient and I would probably go with what @Eran suggested:

List<SomeObject> list = Collections.nCopies(70, someObject);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download