I have a list of concrete objects. While iterating over this list, I'm trying to update an object from it by adding values and I'm getting of course a ConcurentModificationException: What are my alternatives? Thank you and appreciate the help. I'm using Java 11.
import lombok.Data;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
public class Test {
public static void main(String[] args) throws IOException {
List<Person> myList = new ArrayList<>();
List<Hobby> hobbies = new ArrayList<>();
Hobby h1 = new Hobby("SKI");
Hobby h2 = new Hobby("reading");
hobbies.add(h1);
hobbies.add(h2);
Person p = new Person("R", hobbies);
Person p1 = new Person("M", hobbies);
myList.add(p);
myList.add(p1);
myList
.forEach(currentElement -> {
if (Objects.isNull(currentElement.getHobbies())) {
currentElement.setHobbies(Collections.singletonList(new Hobby("NOTHING")));
} else {
currentElement.getHobbies()
.forEach(hobby -> {
if (hobby.getMyHobby().equals("SKI")) {
currentElement.getHobbies().add(new Hobby("SAILING"));
} else {
hobby.getMyHobby().toLowerCase();
}
});
}
});
}
@Data
static
class Person {
String name;
List<Hobby> hobbies;
public Person(String name, List<Hobby> hobbies) {
this.name = name;
this.hobbies = hobbies;
}
}
@Data
static class Hobby {
String myHobby;
public Hobby(String myHobby) {
this.myHobby = myHobby;
}
}
}
CodePudding user response:
You can iterate over the indexes instead:
for (int i = 0; i < currentElement.getHobbies().size(); i ) {
Hobby hobby = currentElement.getHobbies().get(i);
if (hobby.getMyHobby().equals("SKI")) {
currentElement.getHobbies().add(new Hobby("SAILING"));
} else {
hobby.getMyHobby().toLowerCase(); // sic
}
}