Reputation: 233
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?
Upvotes: 4
Views: 9059
Reputation: 98
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.
Upvotes: -1
Reputation: 56423
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..
Upvotes: 7