The trick is that this object MediaContainerModel
inherits equals(Object)
directly from Object
and I can't and don't want to override equals
in its class definition. This is what I have at the moment:
private void addMediaContainer(MediaContainerModel newMediaContainer, ProductModel product) {
List<MediaContainerModel> galleryImages = new ArrayList<>(product.getGalleryImages());
MediaContainerModel inserted = null;
// if a MediaContainer with same qualifier as newMediaContainer already exists, replace it
// with the new one to prevent duplicates
for (int i = 0; i < galleryImages.size(); i++) {
if (galleryImages.get(i).getQualifier().equals(newMediaContainer.getQualifier())) {
inserted = galleryImages.set(i, newMediaContainer);
}
}
// if not, add it
if (inserted == null) {
galleryImages.add(newMediaContainer);
galleryImages.sort((image1, image2) -> image2.getQualifier().compareTo(image1.getQualifier()));
}
product.setGalleryImages(galleryImages);
}
I want to do the same thing without the ugly for-loop by overriding MediaContainerModel.equals(Object)
for this method only so I can use List.indexOf(Object)
or something with lambdas. Is this possible in Java? If so how? Thanks!