假设我有一个汽车 list :
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]
最佳答案
Java 8 will (hopefully) have some form of lambda expression, which will make code like this more feasible. (Whether there'll be anything like list comprehensions is another matter.)
你的愿望已经实现了!
---编辑---
哈哈,好像在暗示:forEach()
一定要看看这个。
针对您的问题,具体如下:
// Suppose that I have already init the list of car
List<Car> cars = //...
List<String> names = new ArrayList<String>();
// LAMBDA EXPRESSION
cars.forEach( (car) -> names.add(car.getName()) );
他们在这里所做的真是令人难以置信。我很高兴看到它在未来被使用。
---编辑---
我应该早点看到这个,但我忍不住发了贴。
jdk8 中添加的 Stream 功能允许 map method .
// Suppose that I have already init the list of car
List<Car> cars = //...
// LAMBDA EXPRESSION
List<String> names = cars.stream().map( car -> car.getName() ).collect( Collectors.toList() );
更简洁的方法是使用 Java 8 的 method references (oracle doc)。
List<String> names = cars.stream().map( Car::getName ).collect( Collectors.toList() );
关于java - 如何在 List 的每个元素上调用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7221833/