How can I create a list with N objects?

泪湿孤枕 提交于 2020-07-02 07:25:41

问题


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)
{

}

回答1:


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)



回答2:


You could use Stream.generate(Supplier<T>) in combination with a reference to a constructor and then use Stream.limit(long) to specify how many you should construct:

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

At least to me, this is more readable and illustrates intent much more clearly than using an IntStream for iteration does as e.g. Alberto Trindade Tavares suggested.

If you want something which performs better in terms of complexity and memory usage, pass the result size to Stream.collect(Collector<? super T,A,R>):

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



回答3:


Why not keep it simple?? If you want to use LINQ or a Lambda it definetly is possible but the question is if it is more readable or maintainable.

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

If you insist this can be the lambda:

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

Creds to @Alberto Trindade since he posted it faster than me.




回答4:


An equivalent implementation of the C# code you mentioned in Java 8, with streams, is the following (EDIT to use mapToObj, suggested by @Eugene):

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



回答5:


If you don't mind a third-party dependency, the following will work with Eclipse Collections:

List<Object> objects = Lists.mutable.withNValues(10, Object::new);
Verify.assertSize(10, objects);

Note: I am a committer for Eclipse Collections.



来源:https://stackoverflow.com/questions/45275402/how-can-i-create-a-list-with-n-objects

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