У мене була дещо інша проблема. Замість збільшення локальної змінної у 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" остаточним, але я не отримав помилок компіляції, залишаючи ці дані такими, які є.