我想使用现有列表中的某些属性从现有对象列表生成对象列表。
例如,
我有List<Car> cars
public Class Car {
Integer carId;
String carName;
Integer engineId;
String engineName;
Double engineCapacity;
}
Class Engine {
Integer engineId;
String engineName;
Double engineCapacity;
}
我想从现有的汽车列表中创建List<Engine> engines
,这样对于每个Car对象,列表中将有一个引擎对象,其中所有属性都使用汽车列表填充。这是否可以使用Java 8 stream / Lambda。
答案 0 :(得分:4)
实际上将汽车列表映射到他们的引擎列表应该已经足够了,因为我已经填充了它们。
List<Engine> = cars.stream().map(Car::getEngine).collect(Collectors.toList());
您应该知道,这些引擎是对汽车对象中引擎的引用。因此,通过汽车改变他们的属性也应反映在引擎列表中。
如果您想拥有不同的引擎对象(但保持与汽车引擎相同的值),您应该尝试kocko的答案。
答案 1 :(得分:3)
这是否可以使用Java 8流?
当然。您只需.map
个Car
到Engine
List<Engine> = cars.stream()
.map(x -> new Engine(x.getEngineId(), x.getEngineName(), x.getEngineCapacity())
.collect(Collectors.toList());
。类似的东西:
Engine(Integer engineId, String engineName, Double engineCapacity)
当然,您必须为Engine
类提供// src/AppBundle/Entity/Parent.php
function __construct() {
$this->children = new \Doctrine\Common\Collections\ArrayCollection();
}
构造函数。
答案 2 :(得分:0)
您可以使用已经描述的流(这是一个优雅的解决方案)
List<Engine> = cars.stream().map(Car::getEngine).collect(Collectors.toList());
或者您只是创建一个新列表,遍历旧列表并将元素添加到新列表中:
List<Engine> l = new LinkedList();
for (Car car : cars) {
l.add(car.getEngine());
}