如何在 List 的每个元素上调用方法?
2022-08-31 19:45:06
假设我有一个汽车列表:
public class Car {
private String brand;
private String name;
private String color;
public Car() { // ... }
public getName() { return name; }
// ...
}
// Suppose that I have already init the list of car
List<Car> cars = //...
List<String> names = new ArrayList<String>();
for (Car c : cars ) {
names.add(c.getName());
}
如何缩短上面的代码?简而言之,如何在List的每个元素上调用方法?
例如,在Python中:
[car.name for car in cars]