我有一个对象列表。我想用一个方法从这个列表中创建单独的对象,而不是总是调用:personList.get(0), personList.get(1)等等。对象名称应该是来自列表元素的Person名称。
List<Person> personList = ...;
我希望能够遍历personList并为列表中的每个对象按名称创建新对象。Person类包含一个带有getter的name属性。我该如何做到这一点?
我有一个对象列表。我想用一个方法从这个列表中创建单独的对象,而不是总是调用:personList.get(0), personList.get(1)等等。对象名称应该是来自列表元素的Person名称。
List<Person> personList = ...;
map
操作:personList.stream()
.map(x -> new T(x.getName()))
.collect(Collectors.toList());
在这里,T
是你想要创建的新元素类型,例如 Student
、Person
、Employee
等。
只是一个简单的forEach循环:
personList.forEach(p -> {
T newObject = new T(p.getName());
// Do what you need to do with each new object
});
如果你想要做更复杂的事情,那么Aonminè的回答可能是你真正需要的。