Modifying local variable from inside lambda

后端 未结 11 1234
失恋的感觉
失恋的感觉 2020-11-28 04:30

Modifying a local variable in forEach gives a compile error:

Normal

    int ordinal = 0;
    for (Example s : list) {
          


        
11条回答
  •  春和景丽
    2020-11-28 05:08

    I had a slightly different problem. Instead of incrementing a local variable in the forEach, I needed to assign an object to the local variable.

    I solved this by defining a private inner domain class that wraps both the list I want to iterate over (countryList) and the output I hope to get from that list (foundCountry). Then using Java 8 "forEach", I iterate over the list field, and when the object I want is found, I assign that object to the output field. So this assigns a value to a field of the local variable, not changing the local variable itself. I believe that since the local variable itself is not changed, the compiler doesn't complain. I can then use the value that I captured in the output field, outside of the list.

    Domain Object:

    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;
        }
    }
    

    Wrapper object:

    private class CountryFound{
        private final List countryList;
        private Country foundCountry;
        public CountryFound(List countryList, Country foundCountry){
            this.countryList = countryList;
            this.foundCountry = foundCountry;
        }
        public List getCountryList() {
            return countryList;
        }
        public void setCountryList(List countryList) {
            this.countryList = countryList;
        }
        public Country getFoundCountry() {
            return foundCountry;
        }
        public void setFoundCountry(Country foundCountry) {
            this.foundCountry = foundCountry;
        }
    }
    

    Iterate operation:

    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());
    

    You could remove the wrapper class method "setCountryList()" and make the field "countryList" final, but I did not get compilation errors leaving these details as-is.

提交回复
热议问题