我有一个稍微不同的问题。我不需要在forEach中增加局部变量,而是需要为该局部变量分配一个对象。
我通过定义一个私有内部域类解决了这一问题,该类既包装了我要迭代的列表(countryList),又包装了希望从该列表中获得的输出(foundCountry)。然后使用Java 8“ forEach”,遍历列表字段,找到所需对象后,将该对象分配给输出字段。因此,这会为局部变量的字段分配一个值,而不更改局部变量本身。我相信,由于局部变量本身未更改,因此编译器不会抱怨。然后,我可以使用在列表之外的输出字段中捕获的值。
域对象:
public class Country {
private int id;
private String countryName;
public Country(int id, String countryName){
this.id = id;
this.countryName = countryName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
}
包装对象:
private class CountryFound{
private final List<Country> countryList;
private Country foundCountry;
public CountryFound(List<Country> countryList, Country foundCountry){
this.countryList = countryList;
this.foundCountry = foundCountry;
}
public List<Country> getCountryList() {
return countryList;
}
public void setCountryList(List<Country> countryList) {
this.countryList = countryList;
}
public Country getFoundCountry() {
return foundCountry;
}
public void setFoundCountry(Country foundCountry) {
this.foundCountry = foundCountry;
}
}
迭代操作:
int id = 5;
CountryFound countryFound = new CountryFound(countryList, null);
countryFound.getCountryList().forEach(c -> {
if(c.getId() == id){
countryFound.setFoundCountry(c);
}
});
System.out.println("Country found: " + countryFound.getFoundCountry().getCountryName());
您可以删除包装器类方法“ setCountryList()”,并将字段“ countryList”定为final,但是我没有遇到编译错误,使这些详细信息保持原样。