JAVA: create a list with n objects

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

Something like that:

List <Objects> getList(int numOfElements)
{

}
+4
source share
4 answers

If I answered correctly:

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 need the same object n times:

Collections.nCopies(n, T)
+9
source

You can use Stream.generate(Supplier<T>)in conjunction with a constructor reference and then use Stream.limit(long)to indicate how much you should build:

Stream.generate(Objects::new).limit(numOfElements).collect(Collectors.toList());    

, , IntStream , . .

-, , Stream.collect(Collector<? super T,A,R>):

Stream.generate(Objects::new).limit(numOfElements).collect(Collectors.toCollection(() -> new ArrayList<>(numOfElements)));
+14

#, Java 8, streams, (EDIT mapToObj, @Eugene):

List <Objects> getList(int numOfElements)
{
  return IntStream.range(0, numOfElements)
                  .mapToObj(x -> new Objects())
                  .collect(Collectors.toList()); 
}
+2

? LINQ Lambda, , , .

List <Objects> getList(int numOfElements)
{
  List<Objects> objectList = new LinkedList<>();
  for(int i = 0; i <= numOfElements; i++)
  {
    objectList.add(new Object());
  }
  return objectList;
}

, :

  return IntStream.range(0, numOfElements)
                  .mapToObj(x -> new Objects())
                  .collect(Collectors.toList()); 

@Alberto Trindade, .

+1

Source: https://habr.com/ru/post/1682100/


All Articles