robert trudel :
In a DTO I have
public class ProductTypesDto extends BaseDto {
private List<Integer> colors = new ArrayList<>();
...
}
In my beans
@Entity
public class ProductTypes
@ManyToMany
private Set<Colors> colors = new HashSet<>();
...
}
An user can add and remove colors for a productTypes
In a DTO to bean conversion, I do
private void convertToBeans(ProductTypesDto dto, ProductTypes beans) {
//add element
for (Integer color : dto.getColors()) {
if (beans.getColors().stream().noneMatch(e -> Objects.equals(e.getId(), color))) {
Optional<Colors> optColors = colorsRepository.findById(color);
if (optColors.isPresent()) {
beans.addColor(optColors.get());
}
}
}
//remove element
for (Iterator<Colors> iterator = beans.getColors().iterator(); iterator.hasNext();) {
Colors color = iterator.next();
if (dto.getColors().stream().noneMatch(e -> e.intValue() == color.getId())) {
Optional<Colors> optColors = colorsRepository.findById(color.getId());
if (optColors.isPresent()) {
beans.removeColor(optColors.get());
}
}
}
}
when code is running, i get
java.util.ConcurrentModificationException: null
Seem like get this on iterator.next();
csunday95 :
Try doing
iterator.remove()
in place of
beans.removeColor(optColors.get());
see the documentation for remove()
. Note the comment
"The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method."