How can I create a list with N objects?

Marci-man :

I am trying to create a list of objects with n elements. I am trying to do this in the most java 8 way as possible. Something similar to the question asked for c# here : Creating N objects and adding them to a list

Something like this:

List <Objects> getList(int numOfElements)
{

}
Eugene :

If I got your question right:

List <Object> getList(int numOfElements){
     return IntStream.range(0, numOfElements)
              .mapToObj(Object::new) // or x -> new Object(x).. or any other constructor 
              .collect(Collectors.toList()); 
}

If you want the same object n times:

Collections.nCopies(n, T)

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=432486&siteId=1