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

好久不见. 提交于 2019-12-11 06:48:39

问题


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++){
   someObjectList.add(someObject);
}

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.


回答1:


You can build the stream manually:

List<SomeObject> list = Stream.generate(() -> someObject).limit(70).collect(toList());
//or if you want to make sure you get an ArrayList:
List<SomeObject> list = Stream.generate(() -> someObject).limit(70).collect(toCollection(ArrayList::new));

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);
//or if you want to make sure you get an ArrayList:
List<SomeObject> list = new ArrayList<> (Collections.nCopies(70, someObject));



回答2:


You can basically use IntStream.range() and map every int to the same object with mapToObj method and collect it to a list



来源:https://stackoverflow.com/questions/40258194/java-8-what-is-the-correct-way-to-fill-an-arraylist-with-the-same-object-using

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!