나는 약간 다른 문제가 있었다. 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"필드를 최종적으로 만들 수 있지만 이러한 세부 정보를 그대로 유지하면서 컴파일 오류가 발생하지 않았습니다.