4

I have a list of objects. I would like to create individual objects from this list with a method and not calling always: personList.get(0), personList.get(1), etc. The object name should be the Person name from the list element.

List<Person> personList = ...;

I'd like to iterate over the personList and create new objects by name for each object from the list.

Person class contains name attribute with a getter.

How can I do that?

3
  • You want to return a list of Person where the persons object have only name! or what exactly? Commented Jun 27, 2018 at 18:44
  • your question is not very clear. Can you mention a sample list input and the sample expected output? What do you mean by "it works case by case"? what is not working in the above case? Commented Jun 27, 2018 at 19:04
  • I updated the description, and remove the misleading code. Hope it is clear now. Thanks! Commented Jun 27, 2018 at 19:56

2 Answers 2

7

Just stream the list and invoke the map operation as follows:

personList.stream()
          .map(x -> new T(x.getName()))
          .collect(Collectors.toList());

Where T is the new type of elements you want to create e.g. Student, Person, Employee etc..

Sign up to request clarification or add additional context in comments.

3 Comments

but the collect is collecting to a list. My main point is to go through the list and get every elements as a new Person object. Or did I miss something? Thanks!
@arena Which is exactly what the code is doing. Going through all the elements and constructing new objects with the people names. If you don’t collect the new elements to a list then where will you store the new objects constructed ?
Make sense! Thanks!
-1

Just a simple forEach loop:

personList.forEach(p -> {
  T newObject = new T(p.getName());
  // Do what you need to do with each new object
});

If you are trying to do something more complicated, then Aonminè's answer is probably what you really need.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.