我有一个对象列表,我想为列表中的每个对象填充一个属性。 我可以像这样使用for循环。
for(Car car : cars) {
String abcd = getSomeValue();
car.setAbcd(abcd);
}
我可以在Java8中使用Lambda做同样的事情。
答案 0 :(得分:9)
是的,您可以使用cars.forEach(c -> c.setAbcd(getSomeValue()));
:
int currentSpeed; //this will store your speed
int[] gearSpeeds = new int[]{40,80,120,160,220}; //set any number of gears and on what speeds will they switch to different gear
int currentGear = 1; //this is default value
for(int i = 0; i < gearSpeeds.Length; i++) //go through hearSpeeds array
if(currentSpeed > gearSpeeds[i]) currentGear++; //if the gear is not enough for specific speed check next it finds the right one
else break;